Skip to main content

buoyant_kernel/schema/
mod.rs

1//! Definitions and functions to create and manipulate kernel schema
2
3use std::borrow::Cow;
4use std::collections::{HashMap, HashSet};
5use std::fmt::{Debug, Display, Formatter};
6use std::iter::{DoubleEndedIterator, FusedIterator};
7use std::str::FromStr;
8use std::sync::{Arc, LazyLock};
9
10use delta_kernel_derive::internal_api;
11use indexmap::IndexMap;
12use itertools::Itertools;
13use serde::{Deserialize, Serialize};
14use tracing::warn;
15
16// re-export because many call sites that use schemas do not necessarily use expressions
17pub(crate) use crate::expressions::{column_name, ColumnName};
18use crate::reserved_field_ids::FILE_NAME;
19use crate::table_features::{get_field_column_mapping_info, ColumnMappingMode};
20use crate::transforms::SchemaTransform;
21use crate::utils::require;
22use crate::{DeltaResult, Error};
23
24pub(crate) mod compare;
25#[cfg(feature = "schema-diff")]
26pub(crate) mod diff;
27
28#[cfg(feature = "internal-api")]
29pub mod derive_macro_utils;
30#[cfg(not(feature = "internal-api"))]
31pub(crate) mod derive_macro_utils;
32pub(crate) mod validation;
33pub(crate) mod variant_utils;
34
35pub type Schema = StructType;
36pub type SchemaRef = Arc<StructType>;
37
38/// Converts a type to a [`Schema`] that represents that type. Derivable for struct types using the
39/// [`delta_kernel_derive::ToSchema`] derive macro.
40#[internal_api]
41pub(crate) trait ToSchema {
42    fn to_schema() -> StructType;
43}
44
45#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
46#[serde(untagged)]
47pub enum MetadataValue {
48    Number(i64),
49    String(String),
50    Boolean(bool),
51    // The [PROTOCOL](https://github.com/delta-io/delta/blob/master/PROTOCOL.md#struct-field) states
52    // only that the metadata is "A JSON map containing information about this column.", so we can
53    // actually have any valid json here. `Other` is therefore a catchall for things we don't need
54    // to handle.
55    Other(serde_json::Value),
56}
57
58impl Display for MetadataValue {
59    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
60        match self {
61            MetadataValue::Number(n) => write!(f, "{n}"),
62            MetadataValue::String(s) => write!(f, "{s}"),
63            MetadataValue::Boolean(b) => write!(f, "{b}"),
64            MetadataValue::Other(v) => write!(f, "{v}"), // just write the json back
65        }
66    }
67}
68
69impl From<String> for MetadataValue {
70    fn from(value: String) -> Self {
71        Self::String(value)
72    }
73}
74
75impl From<&String> for MetadataValue {
76    fn from(value: &String) -> Self {
77        Self::String(value.clone())
78    }
79}
80
81impl From<&str> for MetadataValue {
82    fn from(value: &str) -> Self {
83        Self::String(value.to_string())
84    }
85}
86
87impl From<i64> for MetadataValue {
88    fn from(value: i64) -> Self {
89        Self::Number(value)
90    }
91}
92
93impl From<bool> for MetadataValue {
94    fn from(value: bool) -> Self {
95        Self::Boolean(value)
96    }
97}
98
99#[derive(Debug)]
100pub enum ColumnMetadataKey {
101    ColumnMappingId,
102    ColumnMappingPhysicalName,
103    ParquetFieldId,
104    GenerationExpression,
105    IdentityStart,
106    IdentityStep,
107    IdentityHighWaterMark,
108    IdentityAllowExplicitInsert,
109    InternalColumn,
110    Invariants,
111    MetadataSpec,
112}
113
114impl AsRef<str> for ColumnMetadataKey {
115    fn as_ref(&self) -> &str {
116        match self {
117            Self::ColumnMappingId => "delta.columnMapping.id",
118            Self::ColumnMappingPhysicalName => "delta.columnMapping.physicalName",
119            // "parquet.field.id" is not defined by the Delta protocol, but follows the convention
120            // established by delta-spark and other Delta ecosystem implementations for storing
121            // Parquet field IDs in StructField metadata.
122            Self::ParquetFieldId => "parquet.field.id",
123            Self::GenerationExpression => "delta.generationExpression",
124            Self::IdentityAllowExplicitInsert => "delta.identity.allowExplicitInsert",
125            Self::IdentityHighWaterMark => "delta.identity.highWaterMark",
126            Self::IdentityStart => "delta.identity.start",
127            Self::IdentityStep => "delta.identity.step",
128            Self::InternalColumn => "delta.isInternalColumn",
129            Self::Invariants => "delta.invariants",
130            Self::MetadataSpec => "delta.metadataSpec",
131        }
132    }
133}
134
135/// Enumeration of metadata columns recognized by Delta Kernel.
136///
137/// Metadata columns provide additional information about rows in a Delta table.
138#[derive(Debug, PartialEq, Eq, Hash, Clone, Copy)]
139pub enum MetadataColumnSpec {
140    RowIndex,
141    RowId,
142    RowCommitVersion,
143    FilePath,
144}
145
146impl MetadataColumnSpec {
147    /// A human-readable name for the specified metadata column.
148    pub fn text_value(&self) -> &'static str {
149        match self {
150            Self::RowIndex => "row_index",
151            Self::RowId => "row_id",
152            Self::RowCommitVersion => "row_commit_version",
153            Self::FilePath => "_file",
154        }
155    }
156
157    /// The data type of the specified metadata column.
158    pub fn data_type(&self) -> DataType {
159        match self {
160            Self::RowIndex => DataType::LONG,
161            Self::RowId => DataType::LONG,
162            Self::RowCommitVersion => DataType::LONG,
163            Self::FilePath => DataType::STRING,
164        }
165    }
166
167    /// Whether the specified metadata column is nullable.
168    pub fn nullable(&self) -> bool {
169        match self {
170            Self::RowIndex => false,
171            Self::RowId => false,
172            Self::RowCommitVersion => false,
173            Self::FilePath => false,
174        }
175    }
176
177    /// The reserved field ID for the specified metadata column, if any.
178    pub fn reserved_field_id(&self) -> Option<i64> {
179        match self {
180            Self::FilePath => Some(FILE_NAME),
181            _ => None,
182        }
183    }
184}
185
186impl FromStr for MetadataColumnSpec {
187    type Err = Error;
188
189    fn from_str(s: &str) -> Result<Self, Self::Err> {
190        match s {
191            "row_index" => Ok(Self::RowIndex),
192            "row_id" => Ok(Self::RowId),
193            "row_commit_version" => Ok(Self::RowCommitVersion),
194            "_file" => Ok(Self::FilePath),
195            _ => Err(Error::Schema(format!("Unknown metadata column spec: {s}"))),
196        }
197    }
198}
199
200#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
201pub struct StructField {
202    /// Name of this (possibly nested) column
203    pub name: String,
204    /// The data type of this field
205    #[serde(rename = "type")]
206    pub data_type: DataType,
207    /// Denotes whether this Field can be null
208    pub nullable: bool,
209    /// A JSON map containing information about this column
210    pub metadata: HashMap<String, MetadataValue>,
211}
212
213impl StructField {
214    /// The name of the default row index metadata column.
215    ///
216    /// Note that the dot does not indicate a nested field, it is just a separator for the metadata
217    /// column name.
218    const DEFAULT_ROW_INDEX_COLUMN_NAME: &'static str = "_metadata.row_index";
219
220    /////////////////
221    // Static methods
222    /////////////////
223
224    /// Creates a new field
225    pub fn new(name: impl Into<String>, data_type: impl Into<DataType>, nullable: bool) -> Self {
226        Self {
227            name: name.into(),
228            data_type: data_type.into(),
229            nullable,
230            metadata: HashMap::default(),
231        }
232    }
233
234    /// Creates a new nullable field
235    pub fn nullable(name: impl Into<String>, data_type: impl Into<DataType>) -> Self {
236        Self::new(name, data_type, true)
237    }
238
239    /// Creates a new non-nullable field
240    pub fn not_null(name: impl Into<String>, data_type: impl Into<DataType>) -> Self {
241        Self::new(name, data_type, false)
242    }
243
244    /// Creates a metadata column of the given spec with the given name.
245    pub fn create_metadata_column(name: impl Into<String>, spec: MetadataColumnSpec) -> Self {
246        let mut metadata = HashMap::new();
247        metadata.insert(
248            ColumnMetadataKey::MetadataSpec.as_ref().to_string(),
249            MetadataValue::String(spec.text_value().to_string()),
250        );
251
252        Self {
253            name: name.into(),
254            data_type: spec.data_type(),
255            nullable: spec.nullable(),
256            metadata,
257        }
258    }
259
260    /// Returns the default row index metadata column used by Kernel.
261    pub fn default_row_index_column() -> &'static StructField {
262        static DEFAULT_ROW_INDEX_COLUMN: LazyLock<StructField> = LazyLock::new(|| {
263            StructField::create_metadata_column(
264                StructField::DEFAULT_ROW_INDEX_COLUMN_NAME,
265                MetadataColumnSpec::RowIndex,
266            )
267        });
268        &DEFAULT_ROW_INDEX_COLUMN
269    }
270
271    ///////////////////
272    // Instance methods
273    ///////////////////
274
275    /// Replaces `self.metadata` with the list of <key, value> pairs in `metadata`.
276    pub fn with_metadata(
277        mut self,
278        metadata: impl IntoIterator<Item = (impl Into<String>, impl Into<MetadataValue>)>,
279    ) -> Self {
280        self.metadata = metadata
281            .into_iter()
282            .map(|(k, v)| (k.into(), v.into()))
283            .collect();
284        self
285    }
286
287    /// Extends `self.metadata` to include the <key, value> pairs in `metadata`.
288    pub fn add_metadata(
289        mut self,
290        metadata: impl IntoIterator<Item = (impl Into<String>, impl Into<MetadataValue>)>,
291    ) -> Self {
292        self.metadata
293            .extend(metadata.into_iter().map(|(k, v)| (k.into(), v.into())));
294        self
295    }
296
297    /// Returns true if this field is a metadata column.
298    pub fn is_metadata_column(&self) -> bool {
299        self.metadata
300            .contains_key(ColumnMetadataKey::MetadataSpec.as_ref())
301    }
302
303    /// Returns the metadata column spec if this is a metadata column, otherwise returns None.
304    pub fn get_metadata_column_spec(&self) -> Option<MetadataColumnSpec> {
305        match self
306            .metadata
307            .get(ColumnMetadataKey::MetadataSpec.as_ref())?
308        {
309            MetadataValue::String(s) => MetadataColumnSpec::from_str(s).ok(),
310            _ => None,
311        }
312    }
313
314    /// Returns true if this field is an internal column added by Kernel.
315    ///
316    /// Internal columns must be removed before returning scan results to the user.
317    pub fn is_internal_column(&self) -> bool {
318        matches!(
319            self.metadata
320                .get(ColumnMetadataKey::InternalColumn.as_ref()),
321            Some(MetadataValue::Boolean(true))
322        )
323    }
324
325    /// Marks this field as an internal column.
326    pub fn as_internal_column(self) -> Self {
327        self.add_metadata(vec![(
328            ColumnMetadataKey::InternalColumn.as_ref().to_string(),
329            MetadataValue::Boolean(true),
330        )])
331    }
332
333    pub fn get_config_value(&self, key: &ColumnMetadataKey) -> Option<&MetadataValue> {
334        self.metadata.get(key.as_ref())
335    }
336
337    /// Get the physical name for this field as it should be read from parquet.
338    ///
339    /// When `column_mapping_mode` is `None`, always returns the logical name (even if physical
340    /// name metadata is present). When mode is `Id` or `Name`, returns the physical name from
341    /// metadata if present, otherwise returns the logical name.
342    ///
343    /// NOTE: Caller affirms that the schema was already validated by
344    /// [`crate::table_configuration::TableConfiguration::try_new`], to ensure that annotations are
345    /// always and only present when column mapping mode is enabled.
346    #[internal_api]
347    pub(crate) fn physical_name(&self, column_mapping_mode: ColumnMappingMode) -> &str {
348        match column_mapping_mode {
349            ColumnMappingMode::None => &self.name,
350            ColumnMappingMode::Id | ColumnMappingMode::Name => {
351                match self
352                    .metadata
353                    .get(ColumnMetadataKey::ColumnMappingPhysicalName.as_ref())
354                {
355                    Some(MetadataValue::String(physical_name)) => physical_name,
356                    _ => &self.name,
357                }
358            }
359        }
360    }
361
362    /// Returns true if this field has a physical name annotation
363    /// in its column mapping metadata.
364    pub(crate) fn has_physical_name_annotation(&self) -> bool {
365        matches!(
366            self.metadata
367                .get(ColumnMetadataKey::ColumnMappingPhysicalName.as_ref()),
368            Some(MetadataValue::String(_))
369        )
370    }
371
372    /// Returns true if this field has a column mapping ID annotation
373    /// in its column mapping metadata.
374    pub(crate) fn has_id_annotation(&self) -> bool {
375        matches!(
376            self.metadata
377                .get(ColumnMetadataKey::ColumnMappingId.as_ref()),
378            Some(MetadataValue::Number(_))
379        )
380    }
381
382    /// Change the name of a field. The field will preserve its data type and nullability. Note that
383    /// this allocates a new field.
384    pub fn with_name(&self, new_name: impl Into<String>) -> Self {
385        StructField {
386            name: new_name.into(),
387            data_type: self.data_type().clone(),
388            nullable: self.nullable,
389            metadata: self.metadata.clone(),
390        }
391    }
392
393    #[inline]
394    pub fn name(&self) -> &String {
395        &self.name
396    }
397
398    #[inline]
399    pub fn is_nullable(&self) -> bool {
400        self.nullable
401    }
402
403    #[inline]
404    pub const fn data_type(&self) -> &DataType {
405        &self.data_type
406    }
407
408    #[inline]
409    pub const fn metadata(&self) -> &HashMap<String, MetadataValue> {
410        &self.metadata
411    }
412
413    /// Convert our metadata into a HashMap<String, String>. Note this copies all the data so can be
414    /// expensive for large metadata
415    pub fn metadata_with_string_values(&self) -> HashMap<String, String> {
416        self.metadata
417            .iter()
418            .map(|(key, val)| (key.clone(), val.to_string()))
419            .collect()
420    }
421
422    /// Applies physical name and field ID mappings to this field.
423    ///
424    /// This function sets the field ID for the physical [`StructField`] only if the
425    /// `column_mapping_mode` is `Id`. The field ID is specified using the
426    /// [`ColumnMetadataKey::ParquetFieldId`] metadata field. Readers should use
427    /// [`ColumnMetadataKey::ParquetFieldId`] to match fields to the Parquet schema.
428    /// If a physical StructField contains a field ID, the reader must resolve columns
429    /// with that ID. Otherwise, the physical StructField's name is used. For details,
430    /// see [`read_parquet_files`].
431    ///
432    /// This function also sets the physical name of a field. If `column_mapping_mode` is
433    /// `Id` or `Name`, this is specified in [`ColumnMetadataKey::ColumnMappingPhysicalName`].
434    /// Otherwise, the field's logical name is used.
435    ///
436    /// Returns an error if a field has invalid or inconsistent column mapping annotations (e.g.
437    /// missing when column mapping is enabled, present when disabled, or wrong type), or if a
438    /// metadata column is encountered (metadata columns should not participate in column mapping).
439    ///
440    /// [`read_parquet_files`]: crate::ParquetHandler::read_parquet_files
441    #[internal_api]
442    pub(crate) fn make_physical(
443        &self,
444        column_mapping_mode: ColumnMappingMode,
445    ) -> DeltaResult<Self> {
446        MakePhysical::new(column_mapping_mode).run_field(self)
447    }
448
449    pub(crate) fn has_invariants(&self) -> bool {
450        self.metadata
451            .contains_key(ColumnMetadataKey::Invariants.as_ref())
452    }
453
454    /// Converts logical schema StructField metadata to physical schema metadata
455    /// based on the specified `column_mapping_mode`.
456    ///
457    /// NOTE: Must not be called on metadata columns, which are not subject to column mapping.
458    ///
459    /// NOTE: Caller affirms that `self` was already validated by
460    /// [`crate::table_features::get_field_column_mapping_info`], to ensure that annotations are
461    /// always and only present when column mapping mode is enabled.
462    fn logical_to_physical_metadata(
463        &self,
464        column_mapping_mode: ColumnMappingMode,
465    ) -> HashMap<String, MetadataValue> {
466        let mut base_metadata = self.metadata.clone();
467        let physical_name_key = ColumnMetadataKey::ColumnMappingPhysicalName.as_ref();
468        let field_id_key = ColumnMetadataKey::ColumnMappingId.as_ref();
469        let parquet_field_id_key = ColumnMetadataKey::ParquetFieldId.as_ref();
470        let field_id = base_metadata.get(ColumnMetadataKey::ColumnMappingId.as_ref());
471        match column_mapping_mode {
472            ColumnMappingMode::Id => {
473                let Some(MetadataValue::Number(fid)) = field_id else {
474                    // `get_field_column_mapping_info` should have verified that this has a field Id
475                    warn!("StructField with name {} is missing field id in the Id column mapping mode", self.name());
476                    debug_assert!(false);
477                    return base_metadata;
478                };
479                // Insert the parquet field id matching the column mapping id
480                base_metadata.insert(
481                    parquet_field_id_key.to_string(),
482                    MetadataValue::Number(*fid),
483                );
484                // Ensure that physical name is present
485                debug_assert!(base_metadata.contains_key(physical_name_key));
486            }
487            ColumnMappingMode::Name => {
488                // Logical metadata should have the column mapping metadata keys
489                debug_assert!(base_metadata.contains_key(physical_name_key));
490                debug_assert!(base_metadata.contains_key(field_id_key));
491
492                // Retain column mapping id and insert parquet field id so that
493                // Parquet files carry field IDs in Name mode as well (matching
494                // the Delta protocol requirement and Delta Spark behaviour).
495                let Some(MetadataValue::Number(fid)) = field_id else {
496                    warn!("StructField with name {} is missing field id in the Name column mapping mode", self.name());
497                    debug_assert!(false);
498                    return base_metadata;
499                };
500                base_metadata.insert(
501                    parquet_field_id_key.to_string(),
502                    MetadataValue::Number(*fid),
503                );
504                // TODO(#1070): Remove nested column ids when they are supported in kernel
505            }
506            ColumnMappingMode::None => {
507                base_metadata.remove(physical_name_key);
508                base_metadata.remove(field_id_key);
509                base_metadata.remove(parquet_field_id_key);
510                // TODO(#1070): Remove nested column ids when they are supported in kernel
511            }
512        }
513        base_metadata
514    }
515}
516
517impl Display for StructField {
518    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
519        let mut metadata_str = String::from("{");
520        let mut first = true;
521        for (k, v) in self.metadata.iter() {
522            if !first {
523                metadata_str.push_str(", ");
524            }
525            first = false;
526            metadata_str.push_str(&format!("{k}: {v:?}"));
527        }
528        metadata_str.push('}');
529        write!(
530            f,
531            "{}: {} (is nullable: {}, metadata: {})",
532            self.name, self.data_type, self.nullable, metadata_str,
533        )
534    }
535}
536
537/// A struct is used to represent both the top-level schema of the table
538/// as well as struct columns that contain nested columns.
539#[derive(Debug, PartialEq, Clone, Eq)]
540pub struct StructType {
541    type_name: String,
542    /// The fields stored in this struct
543    // We use indexmap to preserve the order of fields as they are defined in the schema
544    // while also allowing for fast lookup by name. The alternative is to do a linear search
545    // for each field by name would be potentially quite expensive for large schemas.
546    fields: IndexMap<String, StructField>,
547    /// The metadata columns in this struct
548    // We use a dedicated map for metadata columns to allow for fast lookup without having to
549    // iterate over all fields.
550    metadata_columns: HashMap<MetadataColumnSpec, usize>,
551}
552
553pub struct StructTypeBuilder {
554    fields: IndexMap<String, StructField>,
555}
556
557impl Default for StructTypeBuilder {
558    fn default() -> Self {
559        Self::new()
560    }
561}
562
563impl StructTypeBuilder {
564    pub fn new() -> Self {
565        Self {
566            fields: IndexMap::new(),
567        }
568    }
569
570    pub fn from_schema(schema: &StructType) -> Self {
571        Self {
572            fields: schema.fields.clone(),
573        }
574    }
575
576    pub fn add_field(mut self, field: StructField) -> Self {
577        self.fields.insert(field.name.clone(), field);
578        self
579    }
580
581    pub fn build(self) -> DeltaResult<StructType> {
582        StructType::try_new(self.fields.into_values())
583    }
584
585    pub fn build_arc_unchecked(self) -> Arc<StructType> {
586        Arc::new(StructType::new_unchecked(self.fields.into_values()))
587    }
588}
589
590impl StructType {
591    /// Creates a new [`StructType`] from the given fields.
592    ///
593    /// Returns an error if:
594    /// - the schema contains duplicate field names (case-insensitive; Delta column names are
595    ///   case-insensitive per the protocol)
596    /// - the schema contains duplicate metadata columns
597    /// - the schema contains nested metadata columns
598    pub fn try_new(fields: impl IntoIterator<Item = StructField>) -> DeltaResult<Self> {
599        let mut field_map = IndexMap::new();
600        let mut metadata_columns = HashMap::new();
601        let mut seen_lowercase_names = HashSet::new();
602
603        // Validate each field during insertion
604        for (i, field) in fields.into_iter().enumerate() {
605            // Verify that there are no nested metadata columns
606            if !matches!(field.data_type, DataType::Primitive(_)) {
607                Self::ensure_no_metadata_columns_in_field(&field)?;
608            }
609
610            // Check for duplicate metadata columns
611            if let Some(metadata_column_spec) = field.get_metadata_column_spec() {
612                if metadata_columns.insert(metadata_column_spec, i).is_some() {
613                    return Err(Error::schema(format!(
614                        "Duplicate metadata column: {metadata_column_spec:?}",
615                    )));
616                }
617            }
618
619            // Delta column names are case-insensitive; reject schemas with duplicates that differ
620            // only by case.
621            let key = field.name.to_lowercase();
622            if !seen_lowercase_names.insert(key) {
623                return Err(Error::schema(format!(
624                    "Duplicate field name (case-insensitive): '{}'",
625                    field.name
626                )));
627            }
628
629            field_map.insert(field.name.clone(), field);
630        }
631
632        Ok(Self {
633            type_name: "struct".into(),
634            fields: field_map,
635            metadata_columns,
636        })
637    }
638
639    /// Creates a new [`StructType`] from a fallible iterator of fields.
640    ///
641    /// This constructor collects all fields from the iterator, returning the first error
642    /// encountered, or a new [`StructType`] if all fields are successfully collected and validated.
643    pub fn try_from_results<E: Into<Error>>(
644        fields: impl IntoIterator<Item = Result<StructField, E>>,
645    ) -> DeltaResult<Self> {
646        fields
647            .into_iter()
648            .map(|result| result.map_err(Into::into))
649            .process_results(|iter| Self::try_new(iter))?
650    }
651
652    pub fn builder() -> StructTypeBuilder {
653        StructTypeBuilder::new()
654    }
655
656    /// Creates a new [`StructType`] from the given fields without validating them.
657    ///
658    /// This should only be used when you are sure that the fields are valid.
659    /// Refer to [`StructType::try_new`] for more details on the validation checks.
660    #[internal_api]
661    pub(crate) fn new_unchecked(fields: impl IntoIterator<Item = StructField>) -> Self {
662        let mut field_map = IndexMap::new();
663        let mut metadata_columns = HashMap::new();
664
665        for (i, field) in fields.into_iter().enumerate() {
666            if let Some(metadata_column_spec) = field.get_metadata_column_spec() {
667                metadata_columns.insert(metadata_column_spec, i);
668            }
669            field_map.insert(field.name.clone(), field);
670        }
671
672        Self {
673            type_name: "struct".into(),
674            fields: field_map,
675            metadata_columns,
676        }
677    }
678
679    /// Gets a [`StructType`] containing [`StructField`]s of the given names. The order of fields in
680    /// the returned schema will match the order passed to this function, which can be different
681    /// from this order in this schema. Returns an Err if a specified field doesn't exist.
682    pub fn project_as_struct(&self, names: &[impl AsRef<str>]) -> DeltaResult<StructType> {
683        let fields = names.iter().map(|name| {
684            self.fields
685                .get(name.as_ref())
686                .cloned()
687                .ok_or_else(|| Error::missing_column(name.as_ref()))
688        });
689        Self::try_from_results(fields)
690    }
691
692    /// Gets a [`SchemaRef`] containing [`StructField`]s of the given names. The order of fields in
693    /// the returned schema will match the order passed to this function, which can be different
694    /// from this order in this schema. Returns an Err if a specified field doesn't exist.
695    pub fn project(&self, names: &[impl AsRef<str>]) -> DeltaResult<SchemaRef> {
696        let struct_type = self.project_as_struct(names)?;
697        Ok(Arc::new(struct_type))
698    }
699
700    /// Adds fields to this [`StructType`], returning a new [`StructType`].
701    pub fn add(&self, fields: impl IntoIterator<Item = StructField>) -> DeltaResult<Self> {
702        Self::try_new(self.fields.values().cloned().chain(fields))
703    }
704
705    /// Adds a predefined metadata column to this [`StructType`], returning a new [`StructType`].
706    pub fn add_metadata_column(
707        &self,
708        name: impl Into<String>,
709        spec: MetadataColumnSpec,
710    ) -> DeltaResult<Self> {
711        self.add([StructField::create_metadata_column(name, spec)])
712    }
713
714    /// Returns the index of the field with the given name, or None if not found.
715    pub fn index_of(&self, name: impl AsRef<str>) -> Option<usize> {
716        self.fields.get_index_of(name.as_ref())
717    }
718
719    /// Returns the index of the metadata column with the given spec, or None if not found.
720    pub fn index_of_metadata_column(&self, spec: &MetadataColumnSpec) -> Option<&usize> {
721        self.metadata_columns.get(spec)
722    }
723
724    /// Checks if the [`StructType`] contains a field with the specified name.
725    pub fn contains(&self, name: impl AsRef<str>) -> bool {
726        self.fields.contains_key(name.as_ref())
727    }
728
729    /// Checks if the [`StructType`] contains a metadata column with the given spec.
730    pub fn contains_metadata_column(&self, spec: &MetadataColumnSpec) -> bool {
731        self.metadata_columns.contains_key(spec)
732    }
733
734    /// Gets the field with the given name.
735    pub fn field(&self, name: impl AsRef<str>) -> Option<&StructField> {
736        self.fields.get(name.as_ref())
737    }
738
739    /// Resolves a column path through nested structs, returning references to all
740    /// [`StructField`]s along the path. The last element is the leaf field.
741    ///
742    /// Each element of the path must resolve to a field in the current struct. All intermediate
743    /// (non-leaf) fields must be struct types.
744    ///
745    /// Returns an error if the path is empty, a field is not found, or an intermediate
746    /// field is not a struct type.
747    #[internal_api]
748    pub(crate) fn walk_column_fields<'a>(
749        &'a self,
750        col: &ColumnName,
751    ) -> DeltaResult<Vec<&'a StructField>> {
752        self.walk_column_fields_by(col, |s, name| s.field(name))
753    }
754
755    /// Helper to walk through nested columns. For each path component in `col`, calls
756    ///
757    /// `find_field(current_struct, component)` to locate the matching field, then descends
758    ///
759    /// into the next nested struct. Returns references to all [`StructField`]s along the path.
760    pub(crate) fn walk_column_fields_by<'a, F>(
761        &'a self,
762        col: &ColumnName,
763        find_field: F,
764    ) -> DeltaResult<Vec<&'a StructField>>
765    where
766        F: for<'b> Fn(&'b StructType, &str) -> Option<&'b StructField>,
767    {
768        let path = col.path();
769        if path.is_empty() {
770            return Err(Error::generic("Column path cannot be empty"));
771        }
772        let mut current_struct = self;
773        let mut fields = Vec::with_capacity(path.len());
774        for (i, field_name) in path.iter().enumerate() {
775            let field = find_field(current_struct, field_name).ok_or_else(|| {
776                Error::generic(format!(
777                    "Could not resolve column '{col}': field '{field_name}' not found in schema"
778                ))
779            })?;
780            fields.push(field);
781            if i < path.len() - 1 {
782                let DataType::Struct(inner) = field.data_type() else {
783                    return Err(Error::generic(format!(
784                        "Cannot resolve column '{col}': intermediate field '{field_name}' \
785                         is not a struct type"
786                    )));
787                };
788                current_struct = inner;
789            }
790        }
791        Ok(fields)
792    }
793
794    /// Gets the field with the given name and its index.
795    pub fn field_with_index(&self, name: impl AsRef<str>) -> Option<(usize, &StructField)> {
796        self.fields
797            .get_full(name.as_ref())
798            .map(|(index, _, field)| (index, field))
799    }
800
801    /// Gets the field at the given index.
802    pub fn field_at_index(&self, index: usize) -> Option<&StructField> {
803        self.fields.get_index(index).map(|(_, field)| field)
804    }
805
806    /// Gets a reference to all the fields in this struct type.
807    pub fn fields(
808        &self,
809    ) -> impl ExactSizeIterator<Item = &StructField> + DoubleEndedIterator + FusedIterator {
810        self.fields.values()
811    }
812
813    /// Gets an iterator over all the fields in this struct type.
814    pub fn into_fields(
815        self,
816    ) -> impl ExactSizeIterator<Item = StructField> + DoubleEndedIterator + FusedIterator {
817        self.fields.into_values()
818    }
819
820    /// Gets a mutable reference to the underlying field map.
821    pub(crate) fn field_map_mut(&mut self) -> &mut IndexMap<String, StructField> {
822        &mut self.fields
823    }
824
825    /// Walk a pre-segmented column path through this schema and return the leaf field.
826    ///
827    /// `path` is the path's individual name segments (one per nesting level), already split by
828    /// the caller. Lookup at each level is case-insensitive. The Delta protocol uses `.` as the
829    /// dotted-path separator at the API surface, but `field_at_path` itself does not split --
830    /// callers typically pass [`ColumnName::path()`](crate::expressions::ColumnName::path),
831    /// which yields the segments directly.
832    ///
833    /// Panics if any segment is missing or an intermediate field is not a struct. Intended for
834    /// use in test assertions.
835    ///
836    /// # Example
837    ///
838    /// ```ignore
839    /// // Schema:
840    /// //   id:      INTEGER  not null
841    /// //   address: STRUCT { city: STRING not null, zip: STRING }
842    /// let path = vec!["address".to_string(), "city".to_string()];
843    /// let city = schema.field_at_path(&path);
844    /// assert_eq!(city.name(), "city");
845    /// assert!(!city.is_nullable());
846    /// ```
847    #[cfg(any(test, feature = "test-utils"))]
848    #[allow(clippy::panic, clippy::expect_used)]
849    pub fn field_at_path<'a>(&'a self, path: &[String]) -> &'a StructField {
850        fn find_ci<'a>(
851            mut fields: impl Iterator<Item = &'a StructField>,
852            name: &str,
853        ) -> &'a StructField {
854            let lowered = name.to_lowercase();
855            fields
856                .find(|f| f.name().to_lowercase() == lowered)
857                .unwrap_or_else(|| panic!("field '{name}' not found"))
858        }
859        let (first, rest) = path.split_first().expect("non-empty path");
860        let mut field = find_ci(self.fields(), first);
861        for seg in rest {
862            let DataType::Struct(s) = field.data_type() else {
863                panic!("expected struct at intermediate segment '{seg}'");
864            };
865            field = find_ci(s.fields(), seg);
866        }
867        field
868    }
869
870    /// Gets all the field names in this struct type in the order they are defined.
871    pub fn field_names(&self) -> impl ExactSizeIterator<Item = &String> {
872        self.fields.keys()
873    }
874
875    /// Gets the number of fields in this struct type.
876    pub fn num_fields(&self) -> usize {
877        // O(1) for indexmap
878        self.fields.len()
879    }
880
881    /// Recursively counts all [`StructField`] nodes in this schema tree.
882    ///
883    /// This includes nested struct fields (inside Struct, Array, and Map types) but does not
884    /// count Array/Map containers themselves. This matches the traversal pattern used by
885    /// `assign_column_mapping_metadata` when assigning column IDs, so the result equals the
886    /// expected `delta.columnMapping.maxColumnId` for a newly created table.
887    #[allow(unused)] // Only used by integration tests (create_table/column_mapping.rs)
888    #[internal_api]
889    pub(crate) fn total_struct_fields(&self) -> usize {
890        fn count_data_type(dt: &DataType) -> usize {
891            match dt {
892                DataType::Struct(inner) => inner.total_struct_fields(),
893                DataType::Array(array) => count_data_type(array.element_type()),
894                DataType::Map(map) => {
895                    count_data_type(map.key_type()) + count_data_type(map.value_type())
896                }
897                _ => 0,
898            }
899        }
900        self.fields()
901            .map(|field| 1 + count_data_type(field.data_type()))
902            .sum()
903    }
904
905    /// Gets a reference to the metadata column with the given spec.
906    pub fn metadata_column(&self, spec: &MetadataColumnSpec) -> Option<&StructField> {
907        self.metadata_columns
908            .get(spec)
909            .and_then(|index| self.fields.get_index(*index).map(|(_, field)| field))
910    }
911
912    /// Gets an iterator over all the metadata columns in this struct type.
913    pub fn metadata_columns(&self) -> impl Iterator<Item = &StructField> {
914        self.metadata_columns
915            .values()
916            .filter_map(|index| self.fields.get_index(*index).map(|(_, field)| field))
917    }
918
919    /// Extracts the name and type of all leaf columns, in schema order. Caller should pass Some
920    /// `own_name` if this schema is embedded in a larger struct (e.g. `add.*`) and None if the
921    /// schema is a top-level result (e.g. `*`).
922    ///
923    /// NOTE: This method only traverses through `StructType` fields; `MapType` and `ArrayType`
924    /// fields are considered leaves even if they contain `StructType` entries/elements.
925    #[allow(unused)]
926    #[internal_api]
927    pub(crate) fn leaves<'s>(&self, own_name: impl Into<Option<&'s str>>) -> ColumnNamesAndTypes {
928        let mut get_leaves = GetSchemaLeaves::new(own_name.into());
929        get_leaves.transform_struct(self);
930        (get_leaves.names, get_leaves.types).into()
931    }
932
933    /// Applies physical name mappings to this field. If the `column_mapping_mode` is
934    /// [`ColumnMappingMode::Id`], then each StructField will have its parquet field id in the
935    /// [`ColumnMetadataKey::ParquetFieldId`] metadata field.
936    ///
937    /// Uses a single transformer so duplicate column mapping IDs are detected across all
938    /// fields in this struct, not just within each field's subtree.
939    #[internal_api]
940    pub(crate) fn make_physical(
941        &self,
942        column_mapping_mode: ColumnMappingMode,
943    ) -> DeltaResult<Self> {
944        let mut transformer = MakePhysical::new(column_mapping_mode);
945        let fields: Vec<StructField> = self
946            .fields()
947            .map(|field| transformer.run_field(field))
948            .try_collect()?;
949        Self::try_new(fields)
950    }
951
952    /// Validates that there are no metadata columns in the given fields.
953    pub(crate) fn ensure_no_metadata_columns(
954        fields: &mut dyn Iterator<Item = &StructField>,
955    ) -> DeltaResult<()> {
956        for field in fields {
957            Self::ensure_no_metadata_columns_in_field(field)?;
958        }
959        Ok(())
960    }
961
962    /// Validates that there are no metadata columns in the given field.
963    pub(crate) fn ensure_no_metadata_columns_in_field(field: &StructField) -> DeltaResult<()> {
964        if field.is_metadata_column() {
965            return Err(Error::schema(
966                "Metadata columns are only allowed at the top level of a schema".to_string(),
967            ));
968        }
969
970        match &field.data_type {
971            DataType::Struct(struct_type) => {
972                // Only check leaf fields; nested structs were validated at their creation
973                Self::ensure_no_metadata_columns(&mut struct_type.fields().filter(|f| {
974                    !matches!(f.data_type, DataType::Struct(_) | DataType::Variant(_))
975                }))?;
976            }
977            DataType::Array(array_type) => {
978                if let DataType::Struct(struct_type) = array_type.element_type() {
979                    Self::ensure_no_metadata_columns(&mut struct_type.fields())?;
980                }
981            }
982            DataType::Map(map_type) => {
983                if let DataType::Struct(struct_type) = map_type.key_type() {
984                    Self::ensure_no_metadata_columns(&mut struct_type.fields())?;
985                }
986                if let DataType::Struct(struct_type) = map_type.value_type() {
987                    Self::ensure_no_metadata_columns(&mut struct_type.fields())?;
988                }
989            }
990            // Primitive types cannot contain nested metadata columns and variant types are
991            // validated at creation
992            DataType::Primitive(_) | DataType::Variant(_) => {}
993        };
994
995        Ok(())
996    }
997
998    /// Returns a StructType with `new_field` inserted after the field named `after`.
999    /// If `new_field`  already presents in the schema, an error is returned.
1000    /// If `after` is None, `new_field` is appended to the end.
1001    /// If `after` is not found, an error is returned.
1002    pub fn with_field_inserted_after(
1003        mut self,
1004        after: Option<&str>,
1005        new_field: StructField,
1006    ) -> DeltaResult<Self> {
1007        // TODO: Upgrade to a case-insensitive duplicate check when this method is used for
1008        // user-facing operations like ALTER TABLE ADD COLUMN. Currently only used internally
1009        // for inserting protocol-defined fields (e.g. stats_parsed) where exact-name matching
1010        // is sufficient.
1011        if self.fields.contains_key(&new_field.name) {
1012            return Err(Error::generic(format!(
1013                "Field {} already exists",
1014                new_field.name
1015            )));
1016        }
1017
1018        let insert_index = after
1019            .map(|after| {
1020                self.fields
1021                    .get_index_of(after)
1022                    .map(|index| index + 1)
1023                    .ok_or_else(|| Error::generic(format!("Field {after} not found")))
1024            })
1025            .unwrap_or_else(|| Ok(self.fields.len()))?;
1026
1027        self.fields
1028            .insert_before(insert_index, new_field.name.clone(), new_field);
1029        Ok(self)
1030    }
1031
1032    /// Returns a StructType with `new_field` inserted before the field named `before`.
1033    /// If `new_field` already presents in the schema, an error is returned.
1034    /// If `before` is None, `new_field` is inserted at the beginning.
1035    /// If `before` is not found, an error is returned.
1036    pub fn with_field_inserted_before(
1037        mut self,
1038        before: Option<&str>,
1039        new_field: StructField,
1040    ) -> DeltaResult<Self> {
1041        // TODO: Upgrade to a case-insensitive duplicate check when this method is used for
1042        // user-facing operations like ALTER TABLE ADD COLUMN. Currently only used internally
1043        // for inserting protocol-defined fields where exact-name matching is sufficient.
1044        if self.fields.contains_key(&new_field.name) {
1045            return Err(Error::generic(format!(
1046                "Field {} already exists",
1047                new_field.name
1048            )));
1049        }
1050
1051        let index_of_before = before
1052            .map(|before| {
1053                self.fields
1054                    .get_index_of(before)
1055                    .ok_or_else(|| Error::generic(format!("Field {before} not found")))
1056            })
1057            .unwrap_or_else(|| Ok(0))?;
1058
1059        self.fields
1060            .insert_before(index_of_before, new_field.name.clone(), new_field);
1061        Ok(self)
1062    }
1063
1064    /// Returns a StructType with the named field removed.
1065    /// Returns self unchanged if field doesn't exist.
1066    pub fn with_field_removed(mut self, name: &str) -> Self {
1067        self.fields.shift_remove(name);
1068        self
1069    }
1070
1071    /// Returns a new [`StructType`] containing only the top-level fields for which `predicate`
1072    /// returns `true`. This does not recurse into nested [`StructType`] fields.
1073    pub fn with_fields_filtered(
1074        &self,
1075        predicate: impl Fn(&StructField) -> bool,
1076    ) -> DeltaResult<Self> {
1077        Self::try_new(self.fields().filter(|f| predicate(f)).cloned())
1078    }
1079
1080    /// Returns an optional [`StructType`] containing only the top-level fields for which
1081    /// `predicate` returns `true`.
1082    ///
1083    /// This is a convenience wrapper around [`StructType::with_fields_filtered`] for callers
1084    /// that treat an empty top-level struct as "no schema".
1085    pub fn with_fields_filtered_nonempty(
1086        &self,
1087        predicate: impl Fn(&StructField) -> bool,
1088    ) -> DeltaResult<Option<Self>> {
1089        let filtered = self.with_fields_filtered(predicate)?;
1090        if filtered.num_fields() == 0 {
1091            Ok(None)
1092        } else {
1093            Ok(Some(filtered))
1094        }
1095    }
1096
1097    /// Returns a StructType with the named field replaced.
1098    /// Returns an error if field doesn't exist.
1099    pub fn with_field_replaced(
1100        mut self,
1101        name: &str,
1102        new_field: StructField,
1103    ) -> DeltaResult<StructType> {
1104        let replace_field = self
1105            .fields
1106            .get_mut(name)
1107            .ok_or_else(|| Error::generic(format!("Field {name} not found")))?;
1108
1109        *replace_field = new_field;
1110        Ok(self)
1111    }
1112}
1113
1114fn write_indent(f: &mut Formatter<'_>, levels: &[bool]) -> std::fmt::Result {
1115    let mut it = levels.iter().peekable();
1116
1117    while let Some(is_last) = it.next() {
1118        // Final level → draw branch
1119        if it.peek().is_none() {
1120            write!(f, "{}", if *is_last { "└─" } else { "├─" })?;
1121        }
1122        // Parent levels → vertical line or empty space
1123        else {
1124            write!(f, "{}", if *is_last { "   " } else { "│  " })?;
1125        }
1126    }
1127
1128    Ok(())
1129}
1130
1131fn write_struct_type(
1132    st: &StructType,
1133    f: &mut Formatter<'_>,
1134    levels: &mut Vec<bool>,
1135) -> std::fmt::Result {
1136    let len = st.fields.len();
1137
1138    for (i, (_, field)) in st.fields.iter().enumerate() {
1139        let is_last = i + 1 == len;
1140        levels.push(is_last);
1141
1142        write_indent(f, levels)?;
1143        writeln!(f, "{field}")?;
1144
1145        field.data_type.fmt_recursive(f, levels)?;
1146
1147        levels.pop();
1148    }
1149    Ok(())
1150}
1151
1152impl Display for StructType {
1153    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1154        writeln!(f, "{}:", self.type_name)?;
1155        let mut levels = Vec::new();
1156        write_struct_type(self, f, &mut levels)
1157    }
1158}
1159
1160impl IntoIterator for StructType {
1161    type Item = StructField;
1162    type IntoIter = StructFieldIntoIter;
1163
1164    fn into_iter(self) -> Self::IntoIter {
1165        StructFieldIntoIter {
1166            inner: self.fields.into_values(),
1167        }
1168    }
1169}
1170
1171impl<'a> IntoIterator for &'a StructType {
1172    type Item = &'a StructField;
1173    type IntoIter = StructFieldRefIter<'a>;
1174
1175    fn into_iter(self) -> Self::IntoIter {
1176        StructFieldRefIter {
1177            inner: self.fields.values(),
1178        }
1179    }
1180}
1181
1182/// An iterator that yields owned [`StructField`]s from a [`StructType`].
1183///
1184/// This iterator is returned by the [`IntoIterator`] implementation for [`StructType`] and
1185/// consumes the original struct. It yields each field in the order they were defined in the
1186/// schema, preserving the insertion order maintained by the underlying [`IndexMap`].
1187///
1188/// # Examples
1189///
1190/// ```
1191/// # use buoyant_kernel as delta_kernel;
1192/// # use delta_kernel::Error;
1193/// use delta_kernel::schema::{StructType, StructField, DataType};
1194///
1195/// let fields = vec![
1196///     StructField::new("name", DataType::STRING, false),
1197///     StructField::new("age", DataType::INTEGER, true),
1198/// ];
1199/// let struct_type = StructType::try_new(fields)?;
1200///
1201/// // Consume the struct_type and iterate over owned fields
1202/// for field in struct_type {
1203///     println!("Field: {} ({})", field.name(), field.data_type());
1204/// }
1205/// # Ok::<(), Error>(())
1206/// ```
1207///
1208/// [`IndexMap`]: indexmap::IndexMap
1209#[derive(Debug)]
1210pub struct StructFieldIntoIter {
1211    inner: indexmap::map::IntoValues<String, StructField>,
1212}
1213
1214impl Iterator for StructFieldIntoIter {
1215    type Item = StructField;
1216
1217    fn next(&mut self) -> Option<Self::Item> {
1218        self.inner.next()
1219    }
1220
1221    fn size_hint(&self) -> (usize, Option<usize>) {
1222        self.inner.size_hint()
1223    }
1224
1225    fn count(self) -> usize {
1226        self.inner.count()
1227    }
1228
1229    fn last(self) -> Option<Self::Item> {
1230        self.inner.last()
1231    }
1232
1233    fn nth(&mut self, n: usize) -> Option<Self::Item> {
1234        self.inner.nth(n)
1235    }
1236}
1237
1238impl ExactSizeIterator for StructFieldIntoIter {
1239    fn len(&self) -> usize {
1240        self.inner.len()
1241    }
1242}
1243
1244impl FusedIterator for StructFieldIntoIter {}
1245
1246impl DoubleEndedIterator for StructFieldIntoIter {
1247    fn next_back(&mut self) -> Option<Self::Item> {
1248        self.inner.next_back()
1249    }
1250}
1251
1252/// An iterator that yields references to [`StructField`]s from a [`StructType`].
1253///
1254/// This iterator is returned by the [`IntoIterator`] implementation for `&StructType` and by
1255/// the [`StructType::fields()`] method. Unlike [`StructFieldIntoIter`], this iterator does not
1256/// consume the original struct and yields references to the fields. It preserves the insertion
1257/// order maintained by the underlying [`IndexMap`].
1258///
1259/// This iterator implements [`Clone`], allowing you to create multiple independent iterators
1260/// over the same set of fields.
1261///
1262/// # Examples
1263///
1264/// ```
1265/// # use buoyant_kernel as delta_kernel;
1266/// # use delta_kernel::Error;
1267/// use delta_kernel::schema::{StructType, StructField, DataType};
1268///
1269/// let fields = vec![
1270///     StructField::new("name", DataType::STRING, false),
1271///     StructField::new("age", DataType::INTEGER, true),
1272/// ];
1273/// let struct_type = StructType::try_new(fields)?;
1274///
1275/// // Iterate over field references without consuming the struct_type
1276/// for field in &struct_type {
1277///     println!("Field: {} ({})", field.name(), field.data_type());
1278/// }
1279///
1280/// // struct_type is still available for use
1281/// assert_eq!(struct_type.field("name").unwrap().name(), "name");
1282///
1283/// // Or use the fields() method explicitly
1284/// for field in struct_type.fields() {
1285///     println!("Field type: {}", field.data_type());
1286/// }
1287/// # Ok::<(), Error>(())
1288/// ```
1289///
1290/// [`StructType::fields()`]: StructType::fields
1291/// [`IndexMap`]: indexmap::IndexMap
1292#[derive(Debug, Clone)]
1293pub struct StructFieldRefIter<'a> {
1294    inner: indexmap::map::Values<'a, String, StructField>,
1295}
1296
1297impl<'a> Iterator for StructFieldRefIter<'a> {
1298    type Item = &'a StructField;
1299
1300    fn next(&mut self) -> Option<Self::Item> {
1301        self.inner.next()
1302    }
1303
1304    fn size_hint(&self) -> (usize, Option<usize>) {
1305        self.inner.size_hint()
1306    }
1307}
1308
1309impl ExactSizeIterator for StructFieldRefIter<'_> {
1310    fn len(&self) -> usize {
1311        self.inner.len()
1312    }
1313}
1314
1315impl FusedIterator for StructFieldRefIter<'_> {}
1316
1317impl DoubleEndedIterator for StructFieldRefIter<'_> {
1318    fn next_back(&mut self) -> Option<Self::Item> {
1319        self.inner.next_back()
1320    }
1321}
1322
1323struct InvariantChecker(bool);
1324
1325impl<'a> SchemaTransform<'a> for InvariantChecker {
1326    fn transform_struct_field(&mut self, field: &'a StructField) -> Option<Cow<'a, StructField>> {
1327        if field.has_invariants() {
1328            self.0 = true;
1329        } else if !self.0 {
1330            let _ = self.recurse_into_struct_field(field);
1331        }
1332        Some(Cow::Borrowed(field))
1333    }
1334}
1335
1336/// Checks if any column in the schema (including nested columns) has invariants defined.
1337///
1338/// This traverses the entire schema to check for the presence of the `delta.invariants`
1339/// metadata key.
1340pub(crate) fn schema_has_invariants(schema: &Schema) -> bool {
1341    let mut checker = InvariantChecker(false);
1342    let _ = checker.transform_struct(schema);
1343    checker.0
1344}
1345
1346/// Visitor that reports whether any non-null (`nullable: false`) field exists in a schema.
1347/// Walks the full schema tree including nested struct, array element, and map value structs.
1348struct NonNullFieldChecker {
1349    found: bool,
1350}
1351
1352impl<'a> SchemaTransform<'a> for NonNullFieldChecker {
1353    /// Skip recursion into variant internals. The `metadata` and `value` fields inside a
1354    /// `Variant` are protocol-defined, always non-null, and not user-controlled, so they
1355    /// must not be treated as user-declared non-null columns.
1356    fn transform_variant(&mut self, stype: &'a StructType) -> Option<Cow<'a, StructType>> {
1357        Some(Cow::Borrowed(stype))
1358    }
1359
1360    fn transform_struct_field(&mut self, field: &'a StructField) -> Option<Cow<'a, StructField>> {
1361        if !field.is_nullable() {
1362            self.found = true;
1363        } else if !self.found {
1364            let _ = self.recurse_into_struct_field(field);
1365        }
1366        Some(Cow::Borrowed(field))
1367    }
1368}
1369
1370/// Checks if any user-controlled column in the schema (including nested columns) is declared
1371/// non-null (`nullable: false`).
1372///
1373/// Skips `Variant` internal struct fields, which are protocol-defined and always non-null.
1374pub(crate) fn schema_contains_non_null_fields(schema: &Schema) -> bool {
1375    let mut checker = NonNullFieldChecker { found: false };
1376    let _ = checker.transform_struct(schema);
1377    checker.found
1378}
1379
1380/// Normalizes column name field names to match the casing in the schema.
1381///
1382/// Walks each field name through the schema's struct hierarchy, replacing user-provided
1383/// casing with the schema's canonical casing. If a field name isn't found
1384/// case-insensitively, keeps the original (subsequent validation catches it).
1385///
1386/// For example, given schema `{ Id: int, Name: string }` and user-provided columns
1387/// `["id", "name"]`, returns `["Id", "Name"]` -- matching the schema's canonical casing.
1388///
1389/// Note: Must be called before validation (`validate_partition_columns` or
1390/// `validate_clustering_columns`) so that case-normalized names match the schema.
1391pub(crate) fn normalize_column_names_to_schema_casing(
1392    schema: &StructType,
1393    columns: &[ColumnName],
1394) -> Vec<ColumnName> {
1395    columns
1396        .iter()
1397        .map(|col| {
1398            let path = col.path();
1399            let mut normalized: Vec<String> = Vec::with_capacity(path.len());
1400            let mut current_schema = schema;
1401            for (i, field_name) in path.iter().enumerate() {
1402                match current_schema
1403                    .fields()
1404                    .find(|f| f.name().eq_ignore_ascii_case(field_name))
1405                {
1406                    Some(f) => {
1407                        normalized.push(f.name().to_string());
1408                        if let DataType::Struct(inner) = f.data_type() {
1409                            current_schema = inner;
1410                        }
1411                    }
1412                    None => {
1413                        // Field name not found at this level -- keep remaining path
1414                        // unchanged so validation reports the user's original input.
1415                        normalized.extend(path[i..].iter().cloned());
1416                        break;
1417                    }
1418                }
1419            }
1420            ColumnName::new(normalized.iter().map(|s| s.as_str()))
1421        })
1422        .collect()
1423}
1424
1425/// Helper for RowVisitor implementations
1426#[internal_api]
1427#[derive(Clone, Default)]
1428pub(crate) struct ColumnNamesAndTypes(Vec<ColumnName>, Vec<DataType>);
1429impl ColumnNamesAndTypes {
1430    #[internal_api]
1431    pub(crate) fn as_ref(&self) -> (&[ColumnName], &[DataType]) {
1432        (&self.0, &self.1)
1433    }
1434}
1435
1436impl From<(Vec<ColumnName>, Vec<DataType>)> for ColumnNamesAndTypes {
1437    fn from((names, fields): (Vec<ColumnName>, Vec<DataType>)) -> Self {
1438        ColumnNamesAndTypes(names, fields)
1439    }
1440}
1441
1442#[derive(Debug, Deserialize, Serialize)]
1443#[serde(rename_all = "camelCase")]
1444struct StructTypeSerDeHelper {
1445    #[serde(rename = "type")]
1446    type_name: String,
1447    fields: Vec<StructField>,
1448}
1449
1450impl Serialize for StructType {
1451    fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1452    where
1453        S: serde::Serializer,
1454    {
1455        StructTypeSerDeHelper {
1456            type_name: self.type_name.clone(),
1457            fields: self.fields.values().cloned().collect(),
1458        }
1459        .serialize(serializer)
1460    }
1461}
1462
1463impl<'de> Deserialize<'de> for StructType {
1464    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1465    where
1466        D: serde::Deserializer<'de>,
1467        Self: Sized,
1468    {
1469        let helper = StructTypeSerDeHelper::deserialize(deserializer)?;
1470        StructType::try_new(helper.fields).map_err(serde::de::Error::custom)
1471    }
1472}
1473
1474#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
1475#[serde(rename_all = "camelCase")]
1476pub struct ArrayType {
1477    #[serde(rename = "type")]
1478    pub type_name: String,
1479    /// The type of element stored in this array
1480    pub element_type: DataType,
1481    /// Denoting whether this array can contain one or more null values
1482    pub contains_null: bool,
1483}
1484
1485impl ArrayType {
1486    pub fn new(element_type: DataType, contains_null: bool) -> Self {
1487        Self {
1488            type_name: "array".into(),
1489            element_type,
1490            contains_null,
1491        }
1492    }
1493
1494    #[inline]
1495    pub const fn element_type(&self) -> &DataType {
1496        &self.element_type
1497    }
1498
1499    #[inline]
1500    pub const fn contains_null(&self) -> bool {
1501        self.contains_null
1502    }
1503}
1504
1505#[derive(Debug, Serialize, Deserialize, PartialEq, Clone, Eq)]
1506#[serde(rename_all = "camelCase")]
1507pub struct MapType {
1508    #[serde(rename = "type")]
1509    pub type_name: String,
1510    /// The type of element used for the key of this map
1511    pub key_type: DataType,
1512    /// The type of element used for the value of this map
1513    pub value_type: DataType,
1514    /// Denoting whether this map can contain one or more null values
1515    #[serde(default = "default_true")]
1516    pub value_contains_null: bool,
1517}
1518
1519impl MapType {
1520    pub fn new(
1521        key_type: impl Into<DataType>,
1522        value_type: impl Into<DataType>,
1523        value_contains_null: bool,
1524    ) -> Self {
1525        Self {
1526            type_name: "map".into(),
1527            key_type: key_type.into(),
1528            value_type: value_type.into(),
1529            value_contains_null,
1530        }
1531    }
1532
1533    #[inline]
1534    pub const fn key_type(&self) -> &DataType {
1535        &self.key_type
1536    }
1537
1538    #[inline]
1539    pub const fn value_type(&self) -> &DataType {
1540        &self.value_type
1541    }
1542
1543    #[inline]
1544    pub const fn value_contains_null(&self) -> bool {
1545        self.value_contains_null
1546    }
1547
1548    /// Create a schema assuming the map is stored as a struct with the specified key and value
1549    /// field names
1550    pub fn as_struct_schema(&self, key_name: String, val_name: String) -> Schema {
1551        StructType::new_unchecked([
1552            StructField::not_null(key_name, self.key_type.clone()),
1553            StructField::new(val_name, self.value_type.clone(), self.value_contains_null),
1554        ])
1555    }
1556}
1557
1558fn default_true() -> bool {
1559    true
1560}
1561
1562#[derive(Debug, Clone, Copy, Eq, PartialEq, Serialize, Deserialize)]
1563pub struct DecimalType {
1564    precision: u8,
1565    scale: u8,
1566}
1567
1568impl DecimalType {
1569    /// Check if the given precision and scale are valid for a decimal type.
1570    pub fn try_new(precision: u8, scale: u8) -> DeltaResult<Self> {
1571        require!(
1572            0 < precision && precision <= 38,
1573            Error::invalid_decimal(format!(
1574                "precision must be in range 1..38 inclusive, found: {precision}."
1575            ))
1576        );
1577        require!(
1578            scale <= precision,
1579            Error::invalid_decimal(format!(
1580                "scale must be in range 0..{precision} inclusive, found: {scale}."
1581            ))
1582        );
1583        Ok(Self { precision, scale })
1584    }
1585
1586    pub fn precision(&self) -> u8 {
1587        self.precision
1588    }
1589
1590    pub fn scale(&self) -> u8 {
1591        self.scale
1592    }
1593}
1594
1595#[derive(Debug, Serialize, PartialEq, Clone, Eq)]
1596#[serde(rename_all = "camelCase")]
1597pub enum PrimitiveType {
1598    /// UTF-8 encoded string of characters
1599    String,
1600    /// i64: 8-byte signed integer. Range: -9223372036854775808 to 9223372036854775807
1601    Long,
1602    /// i32: 4-byte signed integer. Range: -2147483648 to 2147483647
1603    Integer,
1604    /// i16: 2-byte signed integer numbers. Range: -32768 to 32767
1605    Short,
1606    /// i8: 1-byte signed integer number. Range: -128 to 127
1607    Byte,
1608    /// f32: 4-byte single-precision floating-point numbers
1609    Float,
1610    /// f64: 8-byte double-precision floating-point numbers
1611    Double,
1612    /// bool: boolean values
1613    Boolean,
1614    Binary,
1615    Date,
1616    /// Microsecond precision timestamp, adjusted to UTC.
1617    Timestamp,
1618    #[serde(rename = "timestamp_ntz")]
1619    TimestampNtz,
1620    #[cfg(feature = "nanosecond-timestamps")]
1621    #[serde(rename = "timestamp_nanos")]
1622    TimestampNanos,
1623    #[serde(serialize_with = "serialize_decimal", untagged)]
1624    Decimal(DecimalType),
1625}
1626
1627impl PrimitiveType {
1628    pub fn decimal(precision: u8, scale: u8) -> DeltaResult<Self> {
1629        Ok(DecimalType::try_new(precision, scale)?.into())
1630    }
1631
1632    /// Returns `true` if this primitive type can be widened to the `target` type.
1633    ///
1634    /// Widening rules:
1635    /// - Integer widening: byte -> short -> int -> long (Delta protocol type widening)
1636    /// - Float widening: float -> double (Delta protocol type widening)
1637    /// - Timestamp interchangeability: Timestamp <-> TimestampNtz (both are i64 microseconds since
1638    ///   epoch, differing only in timezone semantics; this is a physical read accommodation, not a
1639    ///   Delta protocol type widening rule)
1640    #[internal_api]
1641    pub(crate) fn can_widen_to(&self, target: &Self) -> bool {
1642        use PrimitiveType::*;
1643        matches!(
1644            (self, target),
1645            // Integer widening: smaller types can be read as larger ones
1646            (Byte, Short | Integer | Long)
1647                | (Short, Integer | Long)
1648                | (Integer, Long)
1649                // Float widening: float can be read as double
1650                | (Float, Double)
1651                // Timestamp equivalence: both are i64 microseconds since epoch, differing only
1652                // in timezone semantics. The parquet representation is identical, so reading
1653                // one as the other is safe at the data layer.
1654                | (Timestamp, TimestampNtz)
1655                | (TimestampNtz, Timestamp)
1656        )
1657    }
1658
1659    /// Returns `true` if `self` is a physical integer type that some checkpoint writers
1660    /// produce when they omit Parquet logical type annotations for date or timestamp columns.
1661    ///
1662    /// Specifically:
1663    /// - Integer -> Date (int32 stored without DATE annotation)
1664    /// - Long -> Timestamp/TimestampNtz (int64 stored without TIMESTAMP annotation)
1665    ///
1666    /// These are **not** Delta protocol type widening rules and must not be used outside of
1667    /// checkpoint compatibility checks.
1668    ///
1669    /// NOTE: The Arrow-level equivalent lives in `check_cast_compat` in
1670    /// `engine/ensure_data_types.rs`. Changes here must be mirrored there.
1671    pub(crate) fn is_checkpoint_cast_compatible(&self, target: &Self) -> bool {
1672        matches!(
1673            (self, target),
1674            (Self::Integer, Self::Date) | (Self::Long, Self::Timestamp | Self::TimestampNtz)
1675        )
1676    }
1677
1678    /// Returns `true` if this primitive type is compatible with `target` for reading
1679    /// `stats_parsed` columns from checkpoint parquet files.
1680    ///
1681    /// This is a superset of [`can_widen_to`]: it includes all Delta protocol type widening
1682    /// rules plus physical Parquet encoding accommodations for checkpoint interop (see
1683    /// [`is_checkpoint_cast_compatible`]).
1684    ///
1685    /// [`can_widen_to`]: PrimitiveType::can_widen_to
1686    /// [`is_checkpoint_cast_compatible`]: PrimitiveType::is_checkpoint_cast_compatible
1687    pub(crate) fn is_stats_type_compatible_with(&self, target: &Self) -> bool {
1688        self == target || self.can_widen_to(target) || self.is_checkpoint_cast_compatible(target)
1689    }
1690}
1691
1692fn serialize_decimal<S: serde::Serializer>(
1693    dtype: &DecimalType,
1694    serializer: S,
1695) -> Result<S::Ok, S::Error> {
1696    serializer.serialize_str(&format!("decimal({},{})", dtype.precision(), dtype.scale()))
1697}
1698
1699fn serialize_variant<S: serde::Serializer>(
1700    _: &StructType,
1701    serializer: S,
1702) -> Result<S::Ok, S::Error> {
1703    serializer.serialize_str("variant")
1704}
1705
1706// Custom Deserialize to provide clear error messages for unsupported types.
1707// The derived impl would produce: "unknown variant `interval second`, expected one of ..."
1708// This impl produces: "Unsupported Delta table type: 'interval second'"
1709impl<'de> serde::Deserialize<'de> for PrimitiveType {
1710    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1711    where
1712        D: serde::Deserializer<'de>,
1713    {
1714        let str_value = String::deserialize(deserializer)?;
1715
1716        match str_value.as_str() {
1717            "string" => Ok(PrimitiveType::String),
1718            "long" => Ok(PrimitiveType::Long),
1719            "integer" => Ok(PrimitiveType::Integer),
1720            "short" => Ok(PrimitiveType::Short),
1721            "byte" => Ok(PrimitiveType::Byte),
1722            "float" => Ok(PrimitiveType::Float),
1723            "double" => Ok(PrimitiveType::Double),
1724            "boolean" => Ok(PrimitiveType::Boolean),
1725            "binary" => Ok(PrimitiveType::Binary),
1726            "date" => Ok(PrimitiveType::Date),
1727            "timestamp" => Ok(PrimitiveType::Timestamp),
1728            "timestamp_ntz" => Ok(PrimitiveType::TimestampNtz),
1729            #[cfg(feature = "nanosecond-timestamps")]
1730            "timestamp_nanos" => Ok(PrimitiveType::TimestampNanos),
1731            decimal_str if decimal_str.starts_with("decimal(") && decimal_str.ends_with(')') => {
1732                // Parse decimal type
1733                let mut parts = decimal_str[8..decimal_str.len() - 1].split(',');
1734                let precision = parts
1735                    .next()
1736                    .and_then(|part| part.trim().parse::<u8>().ok())
1737                    .ok_or_else(|| {
1738                        serde::de::Error::custom(format!(
1739                            "Invalid precision in decimal: {decimal_str}"
1740                        ))
1741                    })?;
1742                let scale = parts
1743                    .next()
1744                    .and_then(|part| part.trim().parse::<u8>().ok())
1745                    .ok_or_else(|| {
1746                        serde::de::Error::custom(format!("Invalid scale in decimal: {decimal_str}"))
1747                    })?;
1748                // Reject extra parts (e.g., decimal(10,2,99))
1749                if parts.next().is_some() {
1750                    return Err(serde::de::Error::custom(format!(
1751                        "Invalid decimal format (expected 2 parts): {decimal_str}"
1752                    )));
1753                }
1754                DecimalType::try_new(precision, scale)
1755                    .map(PrimitiveType::Decimal)
1756                    .map_err(serde::de::Error::custom)
1757            }
1758            unsupported => Err(serde::de::Error::custom(format!(
1759                "Unsupported Delta table type: '{unsupported}'"
1760            ))),
1761        }
1762    }
1763}
1764
1765impl Display for PrimitiveType {
1766    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
1767        match self {
1768            PrimitiveType::String => write!(f, "string"),
1769            PrimitiveType::Long => write!(f, "long"),
1770            PrimitiveType::Integer => write!(f, "integer"),
1771            PrimitiveType::Short => write!(f, "short"),
1772            PrimitiveType::Byte => write!(f, "byte"),
1773            PrimitiveType::Float => write!(f, "float"),
1774            PrimitiveType::Double => write!(f, "double"),
1775            PrimitiveType::Boolean => write!(f, "boolean"),
1776            PrimitiveType::Binary => write!(f, "binary"),
1777            PrimitiveType::Date => write!(f, "date"),
1778            PrimitiveType::Timestamp => write!(f, "timestamp"),
1779            PrimitiveType::TimestampNtz => write!(f, "timestamp_ntz"),
1780            #[cfg(feature = "nanosecond-timestamps")]
1781            PrimitiveType::TimestampNanos => write!(f, "timestamp_nanos"),
1782            PrimitiveType::Decimal(dtype) => {
1783                write!(f, "decimal({},{})", dtype.precision(), dtype.scale())
1784            }
1785        }
1786    }
1787}
1788
1789#[derive(Debug, Serialize, PartialEq, Clone, Eq)]
1790#[serde(untagged, rename_all = "camelCase")]
1791pub enum DataType {
1792    /// UTF-8 encoded string of characters
1793    Primitive(PrimitiveType),
1794    /// An array stores a variable length collection of items of some type.
1795    Array(Box<ArrayType>),
1796    /// A struct is used to represent both the top-level schema of the table as well
1797    /// as struct columns that contain nested columns.
1798    Struct(Box<StructType>),
1799    /// A map stores an arbitrary length collection of key-value pairs
1800    /// with a single keyType and a single valueType
1801    Map(Box<MapType>),
1802    /// The Variant data type. The physical representation can be flexible to support shredded
1803    /// reads. The unshredded schema is `Variant(StructType<metadata: BINARY, value: BINARY>)`.
1804    #[serde(serialize_with = "serialize_variant")]
1805    Variant(Box<StructType>),
1806}
1807
1808impl From<DecimalType> for PrimitiveType {
1809    fn from(dtype: DecimalType) -> Self {
1810        PrimitiveType::Decimal(dtype)
1811    }
1812}
1813impl From<DecimalType> for DataType {
1814    fn from(dtype: DecimalType) -> Self {
1815        PrimitiveType::from(dtype).into()
1816    }
1817}
1818impl From<PrimitiveType> for DataType {
1819    fn from(ptype: PrimitiveType) -> Self {
1820        DataType::Primitive(ptype)
1821    }
1822}
1823impl From<MapType> for DataType {
1824    fn from(map_type: MapType) -> Self {
1825        DataType::Map(Box::new(map_type))
1826    }
1827}
1828
1829impl From<StructType> for DataType {
1830    fn from(struct_type: StructType) -> Self {
1831        DataType::Struct(Box::new(struct_type))
1832    }
1833}
1834
1835impl From<ArrayType> for DataType {
1836    fn from(array_type: ArrayType) -> Self {
1837        DataType::Array(Box::new(array_type))
1838    }
1839}
1840
1841impl From<SchemaRef> for DataType {
1842    fn from(schema: SchemaRef) -> Self {
1843        Arc::unwrap_or_clone(schema).into()
1844    }
1845}
1846
1847// Custom Deserialize to preserve error messages from PrimitiveType.
1848// Serde's untagged enum only reports the last variant's error, discarding PrimitiveType's
1849// clear "Unsupported Delta table type: 'X'" message. We deserialize to Value first, then
1850// dispatch based on structure (string -> Primitive/Variant, object -> Array/Struct/Map).
1851impl<'de> serde::Deserialize<'de> for DataType {
1852    fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1853    where
1854        D: serde::Deserializer<'de>,
1855    {
1856        use serde::de::Error;
1857        use serde_json::Value;
1858
1859        let value = Value::deserialize(deserializer)?;
1860
1861        // String values are either primitive types or "variant"
1862        if let Value::String(s) = &value {
1863            if s == "variant" {
1864                return match DataType::unshredded_variant() {
1865                    DataType::Variant(st) => Ok(DataType::Variant(st)),
1866                    _ => Err(Error::custom("Failed to create variant type")),
1867                };
1868            }
1869
1870            // Try PrimitiveType - this will give us good error messages for unsupported types
1871            return PrimitiveType::deserialize(value.clone())
1872                .map(DataType::Primitive)
1873                .map_err(|e| Error::custom(e.to_string()));
1874        }
1875
1876        // Object values are complex types - dispatch based on "type" field
1877        if let Value::Object(map) = &value {
1878            if let Some(Value::String(type_str)) = map.get("type") {
1879                return match type_str.as_str() {
1880                    "array" => ArrayType::deserialize(value)
1881                        .map(|at| DataType::Array(Box::new(at)))
1882                        .map_err(|e| Error::custom(e.to_string())),
1883                    "struct" => StructType::deserialize(value)
1884                        .map(|st| DataType::Struct(Box::new(st)))
1885                        .map_err(|e| Error::custom(e.to_string())),
1886                    "map" => MapType::deserialize(value)
1887                        .map(|mt| DataType::Map(Box::new(mt)))
1888                        .map_err(|e| Error::custom(e.to_string())),
1889                    _ => Err(Error::custom(format!("Unknown complex type: '{type_str}'"))),
1890                };
1891            }
1892        }
1893
1894        // Fallback error with the actual value that failed
1895        Err(Error::custom(format!(
1896            "Invalid data type: {}",
1897            serde_json::to_string(&value).unwrap_or_else(|_| format!("{value:?}"))
1898        )))
1899    }
1900}
1901
1902/// cbindgen:ignore
1903impl DataType {
1904    pub const STRING: Self = DataType::Primitive(PrimitiveType::String);
1905    pub const LONG: Self = DataType::Primitive(PrimitiveType::Long);
1906    pub const INTEGER: Self = DataType::Primitive(PrimitiveType::Integer);
1907    pub const SHORT: Self = DataType::Primitive(PrimitiveType::Short);
1908    pub const BYTE: Self = DataType::Primitive(PrimitiveType::Byte);
1909    pub const FLOAT: Self = DataType::Primitive(PrimitiveType::Float);
1910    pub const DOUBLE: Self = DataType::Primitive(PrimitiveType::Double);
1911    pub const BOOLEAN: Self = DataType::Primitive(PrimitiveType::Boolean);
1912    pub const BINARY: Self = DataType::Primitive(PrimitiveType::Binary);
1913    pub const DATE: Self = DataType::Primitive(PrimitiveType::Date);
1914    pub const TIMESTAMP: Self = DataType::Primitive(PrimitiveType::Timestamp);
1915    pub const TIMESTAMP_NTZ: Self = DataType::Primitive(PrimitiveType::TimestampNtz);
1916    #[cfg(feature = "nanosecond-timestamps")]
1917    pub const TIMESTAMP_NANOS: Self = DataType::Primitive(PrimitiveType::TimestampNanos);
1918    /// Create a new decimal type with the given precision and scale.
1919    pub fn decimal(precision: u8, scale: u8) -> DeltaResult<Self> {
1920        Ok(PrimitiveType::decimal(precision, scale)?.into())
1921    }
1922
1923    /// Create a new struct type with the given fields.
1924    pub fn try_struct_type(fields: impl IntoIterator<Item = StructField>) -> DeltaResult<Self> {
1925        Ok(StructType::try_new(fields)?.into())
1926    }
1927
1928    /// Create a new struct type from a fallible iterator of fields.
1929    pub fn try_struct_type_from_results<E: Into<Error>>(
1930        fields: impl IntoIterator<Item = Result<StructField, E>>,
1931    ) -> DeltaResult<Self> {
1932        StructType::try_from_results(fields).map(Self::from)
1933    }
1934
1935    /// Create a new struct type with the given fields without validating them.
1936    pub(crate) fn struct_type_unchecked(fields: impl IntoIterator<Item = StructField>) -> Self {
1937        StructType::new_unchecked(fields).into()
1938    }
1939
1940    /// Create a new unshredded [`DataType::Variant`]. This data type is a struct of two not-null
1941    /// binary fields: `metadata` and `value`.
1942    pub fn unshredded_variant() -> Self {
1943        DataType::Variant(Box::new(StructType::new_unchecked([
1944            StructField::not_null("metadata", DataType::BINARY),
1945            StructField::not_null("value", DataType::BINARY),
1946        ])))
1947    }
1948
1949    /// Create a new [`DataType::Variant`] from the provided fields. For unshredded variants, you
1950    /// should prefer using [`DataType::unshredded_variant`].
1951    pub fn variant_type(fields: impl IntoIterator<Item = StructField>) -> DeltaResult<Self> {
1952        // Different from regular StructTypes, Variants are not allowed to contain metadata columns
1953        // at all, so we also need to check their top-level primitive types.
1954        Ok(DataType::Variant(Box::new(StructType::try_from_results(
1955            fields.into_iter().map(|field| {
1956                if field.is_metadata_column() {
1957                    Err(Error::schema(
1958                        "Metadata columns are not allowed in Variant types".to_string(),
1959                    ))
1960                } else {
1961                    Ok(field)
1962                }
1963            }),
1964        )?)))
1965    }
1966
1967    /// Attempt to convert this data type to a [`PrimitiveType`]. Returns `None` if this is a
1968    /// non-primitive type.
1969    pub fn as_primitive_opt(&self) -> Option<&PrimitiveType> {
1970        match self {
1971            DataType::Primitive(ptype) => Some(ptype),
1972            _ => None,
1973        }
1974    }
1975
1976    fn fmt_recursive(&self, f: &mut Formatter<'_>, levels: &mut Vec<bool>) -> std::fmt::Result {
1977        match self {
1978            DataType::Struct(inner) => write_struct_type(inner, f, levels),
1979
1980            DataType::Array(inner) => {
1981                levels.push(true); // only one child → last
1982                write_indent(f, levels)?;
1983                writeln!(f, "array_element: {}", inner.element_type)?;
1984                inner.element_type.fmt_recursive(f, levels)?;
1985                levels.pop();
1986                Ok(())
1987            }
1988
1989            DataType::Map(inner) => {
1990                // key
1991                levels.push(false); // map_key is NOT last
1992                write_indent(f, levels)?;
1993                writeln!(f, "map_key: {}", inner.key_type)?;
1994                inner.key_type.fmt_recursive(f, levels)?;
1995                levels.pop();
1996
1997                // value
1998                levels.push(true); // map_value IS last at this level
1999                write_indent(f, levels)?;
2000                writeln!(f, "map_value: {}", inner.value_type)?;
2001                inner.value_type.fmt_recursive(f, levels)?;
2002                levels.pop();
2003                Ok(())
2004            }
2005
2006            _ => Ok(()),
2007        }
2008    }
2009}
2010
2011impl Display for DataType {
2012    fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result {
2013        match self {
2014            DataType::Primitive(p) => write!(f, "{p}"),
2015            DataType::Array(a) => write!(f, "array<{}>", a.element_type),
2016            DataType::Struct(s) => {
2017                write!(f, "struct<")?;
2018                for (i, field) in s.fields().enumerate() {
2019                    if i > 0 {
2020                        write!(f, ", ")?;
2021                    }
2022                    write!(f, "{}: {}", field.name, field.data_type)?;
2023                }
2024                write!(f, ">")
2025            }
2026            DataType::Map(m) => write!(f, "map<{}, {}>", m.key_type, m.value_type),
2027            DataType::Variant(_) => write!(f, "variant"),
2028        }
2029    }
2030}
2031
2032struct GetSchemaLeaves {
2033    path: Vec<String>,
2034    names: Vec<ColumnName>,
2035    types: Vec<DataType>,
2036}
2037impl GetSchemaLeaves {
2038    fn new(own_name: Option<&str>) -> Self {
2039        Self {
2040            path: own_name.into_iter().map(|s| s.to_string()).collect(),
2041            names: vec![],
2042            types: vec![],
2043        }
2044    }
2045}
2046
2047impl<'a> SchemaTransform<'a> for GetSchemaLeaves {
2048    fn transform_struct_field(&mut self, field: &StructField) -> Option<Cow<'a, StructField>> {
2049        self.path.push(field.name.clone());
2050        if let DataType::Struct(_) = field.data_type {
2051            self.recurse_into_struct_field(field);
2052        } else {
2053            self.names.push(ColumnName::new(&self.path));
2054            self.types.push(field.data_type.clone());
2055        }
2056        self.path.pop();
2057        None
2058    }
2059}
2060
2061struct MakePhysical<'a> {
2062    column_mapping_mode: ColumnMappingMode,
2063    path: Vec<&'a str>,
2064    seen: HashMap<i64, &'a str>,
2065    err: Option<Error>,
2066}
2067impl<'a> MakePhysical<'a> {
2068    fn new(column_mapping_mode: ColumnMappingMode) -> Self {
2069        Self {
2070            column_mapping_mode,
2071            path: vec![],
2072            seen: HashMap::new(),
2073            err: None,
2074        }
2075    }
2076
2077    /// Transforms a single [`StructField`] from logical to physical. Returns the physical
2078    /// field on success, or the first error encountered during the recursive transformation.
2079    fn run_field(&mut self, field: &'a StructField) -> DeltaResult<StructField> {
2080        let result = self.transform_struct_field(field);
2081        match (self.err.take(), result) {
2082            (Some(err), _) => Err(err),
2083            // Theoretically impossible: MakePhysical only returns None when it sets an error
2084            (None, None) => Err(Error::internal_error(
2085                "make_physical: transform returned None without setting an error",
2086            )),
2087            (None, Some(field)) => Ok(field.into_owned()),
2088        }
2089    }
2090
2091    fn transform_inner<T>(
2092        &mut self,
2093        field_name: &'a str,
2094        transform: impl FnOnce(&mut Self) -> Option<T>,
2095    ) -> Option<T> {
2096        if self.err.is_some() {
2097            return None;
2098        }
2099        self.path.push(field_name);
2100        let result = transform(self);
2101        self.path.pop();
2102        result
2103    }
2104}
2105impl<'a> SchemaTransform<'a> for MakePhysical<'a> {
2106    fn transform_array_element(&mut self, etype: &'a DataType) -> Option<Cow<'a, DataType>> {
2107        self.transform_inner("<array element>", |this| this.transform(etype))
2108    }
2109    fn transform_map_key(&mut self, ktype: &'a DataType) -> Option<Cow<'a, DataType>> {
2110        self.transform_inner("<map key>", |this| this.transform(ktype))
2111    }
2112    fn transform_map_value(&mut self, vtype: &'a DataType) -> Option<Cow<'a, DataType>> {
2113        self.transform_inner("<map value>", |this| this.transform(vtype))
2114    }
2115    fn transform_struct_field(&mut self, field: &'a StructField) -> Option<Cow<'a, StructField>> {
2116        self.transform_inner(field.name(), |this| {
2117            let (physical_name, _id) = get_field_column_mapping_info(
2118                field,
2119                this.column_mapping_mode,
2120                &this.path,
2121                Some(&mut this.seen),
2122            )
2123            .map_err(|e| this.err = Some(e))
2124            .ok()?;
2125
2126            if field.is_metadata_column() {
2127                return Some(Cow::Borrowed(field));
2128            }
2129
2130            let field = this.recurse_into_struct_field(field)?;
2131
2132            let metadata = field.logical_to_physical_metadata(this.column_mapping_mode);
2133            let name = physical_name.to_owned();
2134
2135            Some(Cow::Owned(field.with_name(name).with_metadata(metadata)))
2136        })
2137    }
2138
2139    fn transform_variant(&mut self, stype: &'a StructType) -> Option<Cow<'a, StructType>> {
2140        // There is no column mapping metadata inside the struct fields of a variant, so
2141        // we do not recurse into the variant fields
2142        Some(Cow::Borrowed(stype))
2143    }
2144}
2145
2146#[cfg(test)]
2147mod tests {
2148    use rstest::rstest;
2149    use serde_json;
2150
2151    use super::*;
2152    use crate::table_features::ColumnMappingMode;
2153    use crate::utils::test_utils::{
2154        assert_result_error_with_message, test_deep_nested_schema_missing_leaf_cm,
2155    };
2156
2157    fn example_schema_metadata() -> &'static str {
2158        r#"
2159            {
2160                "name": "e",
2161                "type": {
2162                    "type": "array",
2163                    "elementType": {
2164                        "type": "struct",
2165                        "fields": [
2166                            {
2167                                "name": "d",
2168                                "type": "integer",
2169                                "nullable": false,
2170                                "metadata": {
2171                                    "delta.columnMapping.id": 5,
2172                                    "delta.columnMapping.physicalName": "col-a7f4159c-53be-4cb0-b81a-f7e5240cfc49"
2173                                }
2174                            }
2175                        ]
2176                    },
2177                    "containsNull": true
2178                },
2179                "nullable": true,
2180                "metadata": {
2181                    "delta.columnMapping.id": 4,
2182                    "delta.columnMapping.physicalName": "col-5f422f40-de70-45b2-88ab-1d5c90e94db1",
2183                    "delta.identity.start": 2147483648
2184                }
2185            }"#
2186    }
2187
2188    #[test]
2189    fn test_serde_data_types() {
2190        let data = r#"
2191        {
2192            "name": "a",
2193            "type": "integer",
2194            "nullable": false,
2195            "metadata": {}
2196        }
2197        "#;
2198        let field: StructField = serde_json::from_str(data).unwrap();
2199        assert!(matches!(field.data_type, DataType::INTEGER));
2200
2201        let data = r#"
2202        {
2203            "name": "c",
2204            "type": {
2205                "type": "array",
2206                "elementType": "integer",
2207                "containsNull": false
2208            },
2209            "nullable": true,
2210            "metadata": {}
2211        }
2212        "#;
2213        let field: StructField = serde_json::from_str(data).unwrap();
2214        assert!(matches!(field.data_type, DataType::Array(_)));
2215
2216        let data = r#"
2217        {
2218            "name": "e",
2219            "type": {
2220                "type": "array",
2221                "elementType": {
2222                    "type": "struct",
2223                    "fields": [
2224                        {
2225                            "name": "d",
2226                            "type": "integer",
2227                            "nullable": false,
2228                            "metadata": {}
2229                        }
2230                    ]
2231                },
2232                "containsNull": true
2233            },
2234            "nullable": true,
2235            "metadata": {}
2236        }
2237        "#;
2238        let field: StructField = serde_json::from_str(data).unwrap();
2239        assert!(matches!(field.data_type, DataType::Array(_)));
2240        match field.data_type {
2241            DataType::Array(array) => assert!(matches!(array.element_type, DataType::Struct(_))),
2242            _ => unreachable!(),
2243        }
2244
2245        let data = r#"
2246        {
2247            "name": "f",
2248            "type": {
2249                "type": "map",
2250                "keyType": "string",
2251                "valueType": "string",
2252                "valueContainsNull": true
2253            },
2254            "nullable": true,
2255            "metadata": {}
2256        }
2257        "#;
2258        let field: StructField = serde_json::from_str(data).unwrap();
2259        assert!(matches!(field.data_type, DataType::Map(_)));
2260    }
2261
2262    #[test]
2263    fn test_roundtrip_decimal() {
2264        let data = r#"
2265        {
2266            "name": "a",
2267            "type": "decimal(10, 2)",
2268            "nullable": false,
2269            "metadata": {}
2270        }
2271        "#;
2272        let field: StructField = serde_json::from_str(data).unwrap();
2273        assert_eq!(field.data_type, DataType::decimal(10, 2).unwrap());
2274
2275        let json_str = serde_json::to_string(&field).unwrap();
2276        assert_eq!(
2277            json_str,
2278            r#"{"name":"a","type":"decimal(10,2)","nullable":false,"metadata":{}}"#
2279        );
2280    }
2281
2282    #[test]
2283    fn test_roundtrip_variant() {
2284        let data = r#"
2285        {
2286            "name": "v",
2287            "type": "variant",
2288            "nullable": false,
2289            "metadata": {}
2290        }
2291        "#;
2292        let field: StructField = serde_json::from_str(data).unwrap();
2293        assert_eq!(field.data_type, DataType::unshredded_variant());
2294
2295        let json_str = serde_json::to_string(&field).unwrap();
2296        assert_eq!(
2297            json_str,
2298            r#"{"name":"v","type":"variant","nullable":false,"metadata":{}}"#
2299        );
2300    }
2301
2302    #[test]
2303    fn test_unshredded_variant() {
2304        let unshredded_variant_type = DataType::unshredded_variant();
2305
2306        match &unshredded_variant_type {
2307            DataType::Variant(struct_type) => {
2308                let fields: Vec<_> = struct_type.fields().collect();
2309                assert_eq!(fields.len(), 2);
2310
2311                assert_eq!(fields[0].name, "metadata");
2312                assert_eq!(fields[0].data_type, DataType::BINARY);
2313                assert!(!fields[0].nullable);
2314
2315                assert_eq!(fields[1].name, "value");
2316                assert_eq!(fields[1].data_type, DataType::BINARY);
2317                assert!(!fields[1].nullable);
2318            }
2319            _ => panic!("Expected DataType::Variant, got {unshredded_variant_type:?}"),
2320        }
2321    }
2322
2323    #[rstest]
2324    #[case("interval second")]
2325    #[case("interval day")]
2326    #[case("money")]
2327    fn test_unsupported_type_error_message(#[case] unsupported_type: &str) {
2328        let data = format!(
2329            r#"{{
2330                "name": "test_field",
2331                "type": "{unsupported_type}",
2332                "nullable": false,
2333                "metadata": {{}}
2334            }}"#
2335        );
2336        let result: Result<StructField, _> = serde_json::from_str(&data);
2337        assert!(result.is_err());
2338        let err = result.unwrap_err();
2339        let expected_msg = format!("Unsupported Delta table type: '{unsupported_type}'");
2340        assert!(
2341            err.to_string().contains(&expected_msg),
2342            "Expected error message about unsupported type '{unsupported_type}', got: {err}"
2343        );
2344    }
2345
2346    #[rstest]
2347    #[case("string", DataType::STRING)]
2348    #[case("long", DataType::LONG)]
2349    #[case("integer", DataType::INTEGER)]
2350    #[case("short", DataType::SHORT)]
2351    #[case("byte", DataType::BYTE)]
2352    #[case("float", DataType::FLOAT)]
2353    #[case("double", DataType::DOUBLE)]
2354    #[case("boolean", DataType::BOOLEAN)]
2355    #[case("binary", DataType::BINARY)]
2356    #[case("date", DataType::DATE)]
2357    #[case("timestamp", DataType::TIMESTAMP)]
2358    #[case("timestamp_ntz", DataType::TIMESTAMP_NTZ)]
2359    fn test_primitive_type_deserialization_still_works(
2360        #[case] type_str: &str,
2361        #[case] expected_type: DataType,
2362    ) {
2363        let data = format!(
2364            r#"{{
2365                "name": "test_field",
2366                "type": "{type_str}",
2367                "nullable": false,
2368                "metadata": {{}}
2369            }}"#
2370        );
2371        let field: StructField = serde_json::from_str(&data).unwrap();
2372        assert_eq!(field.data_type, expected_type);
2373    }
2374
2375    #[rstest]
2376    #[case(10, 2)]
2377    #[case(16, 4)]
2378    #[case(38, 10)]
2379    fn test_decimal_with_primitive_deserializer(#[case] precision: u8, #[case] scale: u8) {
2380        let data = format!(
2381            r#"{{
2382                "name": "test_decimal",
2383                "type": "decimal({precision},{scale})",
2384                "nullable": false,
2385                "metadata": {{}}
2386            }}"#
2387        );
2388        let field: StructField = serde_json::from_str(&data).unwrap();
2389        assert_eq!(
2390            field.data_type,
2391            DataType::decimal(precision, scale).unwrap()
2392        );
2393    }
2394
2395    #[rstest]
2396    #[case("decimal(invalid)", "Invalid precision in decimal")]
2397    #[case("decimal(10)", "Invalid scale in decimal")]
2398    #[case("decimal()", "Invalid precision in decimal")]
2399    #[case("decimal(10,2,99)", "Invalid decimal format (expected 2 parts)")]
2400    fn test_invalid_decimal_format(#[case] invalid_type: &str, #[case] expected_error: &str) {
2401        let data = format!(
2402            r#"{{
2403                "name": "invalid",
2404                "type": "{invalid_type}",
2405                "nullable": false,
2406                "metadata": {{}}
2407            }}"#
2408        );
2409        let result: Result<StructField, _> = serde_json::from_str(&data);
2410        assert!(result.is_err());
2411        let err = result.unwrap_err();
2412        assert!(
2413            err.to_string().contains(expected_error),
2414            "Expected error containing '{expected_error}', got: {err}"
2415        );
2416    }
2417
2418    #[rstest]
2419    #[case(
2420        r#"{"type": "array", "elementType": "integer", "containsNull": false}"#,
2421        DataType::Array(Box::new(ArrayType::new(DataType::INTEGER, false)))
2422    )]
2423    #[case(
2424        r#"{"type": "struct", "fields": [{"name": "a", "type": "integer", "nullable": false, "metadata": {}}, {"name": "b", "type": "string", "nullable": true, "metadata": {}}]}"#,
2425        DataType::Struct(Box::new(StructType::new_unchecked([
2426            StructField::new("a", DataType::INTEGER, false),
2427            StructField::new("b", DataType::STRING, true),
2428        ])))
2429    )]
2430    #[case(
2431        r#"{"type": "map", "keyType": "string", "valueType": "integer", "valueContainsNull": true}"#,
2432        DataType::Map(Box::new(MapType::new(DataType::STRING, DataType::INTEGER, true)))
2433    )]
2434    #[case("\"string\"", DataType::STRING)]
2435    #[case("\"long\"", DataType::LONG)]
2436    #[case("\"integer\"", DataType::INTEGER)]
2437    #[case("\"short\"", DataType::SHORT)]
2438    #[case("\"byte\"", DataType::BYTE)]
2439    #[case("\"float\"", DataType::FLOAT)]
2440    #[case("\"double\"", DataType::DOUBLE)]
2441    #[case("\"boolean\"", DataType::BOOLEAN)]
2442    #[case("\"binary\"", DataType::BINARY)]
2443    #[case("\"date\"", DataType::DATE)]
2444    #[case("\"timestamp\"", DataType::TIMESTAMP)]
2445    #[case("\"timestamp_ntz\"", DataType::TIMESTAMP_NTZ)]
2446    #[case("\"variant\"", DataType::unshredded_variant())]
2447    fn test_data_type_deserialization(#[case] type_json: &str, #[case] expected: DataType) {
2448        let data_type: DataType = serde_json::from_str(type_json).unwrap();
2449        assert_eq!(data_type, expected);
2450    }
2451
2452    #[test]
2453    fn test_make_physical_no_column_mapping() {
2454        let field = StructField::nullable(
2455            "e",
2456            ArrayType::new(
2457                StructType::new_unchecked([StructField::not_null("d", DataType::INTEGER)]).into(),
2458                true,
2459            ),
2460        );
2461        let physical_field = field.make_physical(ColumnMappingMode::None).unwrap();
2462
2463        assert_eq!(physical_field.name, "e");
2464        assert!(physical_field
2465            .get_config_value(&ColumnMetadataKey::ColumnMappingId)
2466            .is_none());
2467        assert!(physical_field
2468            .get_config_value(&ColumnMetadataKey::ColumnMappingPhysicalName)
2469            .is_none());
2470
2471        let DataType::Array(atype) = physical_field.data_type else {
2472            panic!("Expected an Array");
2473        };
2474        let DataType::Struct(stype) = atype.element_type else {
2475            panic!("Expected a Struct");
2476        };
2477        let struct_field = stype.fields.get_index(0).unwrap().1;
2478        assert_eq!(struct_field.name, "d");
2479    }
2480
2481    #[test]
2482    fn test_make_physical_rejects_annotated_fields_when_column_mapping_disabled() {
2483        let data = example_schema_metadata();
2484        let field: StructField = serde_json::from_str(data).unwrap();
2485        assert!(field.make_physical(ColumnMappingMode::None).is_err());
2486    }
2487
2488    #[test]
2489    fn test_make_physical_rejects_unannotated_leaf_in_deep_nesting() {
2490        let schema = test_deep_nested_schema_missing_leaf_cm();
2491        let field = schema.fields().next().unwrap();
2492        let err = field
2493            .make_physical(ColumnMappingMode::Name)
2494            .unwrap_err()
2495            .to_string();
2496        assert!(
2497            err.contains("top.`<array element>`.mid_field.`<map value>`.leaf"),
2498            "Expected full nested path in error, got: {err}"
2499        );
2500    }
2501
2502    #[test]
2503    fn test_make_physical_rejects_duplicate_column_mapping_ids() {
2504        use crate::schema::ColumnMetadataKey;
2505
2506        fn cm_field(name: &str, id: i64, data_type: impl Into<DataType>) -> StructField {
2507            StructField::not_null(name, data_type).with_metadata([
2508                (
2509                    ColumnMetadataKey::ColumnMappingId.as_ref(),
2510                    MetadataValue::Number(id),
2511                ),
2512                (
2513                    ColumnMetadataKey::ColumnMappingPhysicalName.as_ref(),
2514                    MetadataValue::String(format!("col-{name}")),
2515                ),
2516            ])
2517        }
2518
2519        let inner = StructType::new_unchecked([
2520            cm_field("x", 3, DataType::INTEGER),
2521            cm_field("y", 4, DataType::STRING),
2522        ]);
2523        let schema = StructType::new_unchecked([
2524            cm_field("a", 1, DataType::INTEGER),
2525            cm_field(
2526                "b",
2527                2,
2528                ArrayType::new(DataType::Struct(Box::new(inner)), true),
2529            ),
2530            cm_field("c", 3, DataType::STRING),
2531        ]);
2532        assert_result_error_with_message(
2533            schema.make_physical(ColumnMappingMode::Id),
2534            "Duplicate column mapping ID",
2535        );
2536    }
2537
2538    #[test]
2539    fn test_make_physical_column_mapping() {
2540        [ColumnMappingMode::Name, ColumnMappingMode::Id]
2541            .into_iter()
2542            .for_each(|mode| {
2543                let data = example_schema_metadata();
2544
2545                let field: StructField = serde_json::from_str(data).unwrap();
2546
2547                let col_id = field
2548                    .get_config_value(&ColumnMetadataKey::ColumnMappingId)
2549                    .unwrap();
2550                let id_start = field
2551                    .get_config_value(&ColumnMetadataKey::IdentityStart)
2552                    .unwrap();
2553                assert!(matches!(col_id, MetadataValue::Number(num) if *num == 4));
2554                assert!(matches!(id_start, MetadataValue::Number(num) if *num == 2147483648i64));
2555                assert_eq!(
2556                    field.physical_name(mode),
2557                    "col-5f422f40-de70-45b2-88ab-1d5c90e94db1"
2558                );
2559                let physical_field = field.make_physical(mode).unwrap();
2560
2561                // Parquet field id should only be present in id column mapping mode
2562                match mode {
2563                    ColumnMappingMode::Id => {
2564                        assert!(matches!(
2565                            physical_field.get_config_value(&ColumnMetadataKey::ParquetFieldId),
2566                            Some(MetadataValue::Number(4))
2567                        ));
2568
2569                        assert!(matches!(
2570                            physical_field.get_config_value(&ColumnMetadataKey::ColumnMappingId),
2571                            Some(MetadataValue::Number(4))
2572                        ));
2573                    }
2574                    ColumnMappingMode::Name => {
2575                        assert!(matches!(
2576                            physical_field.get_config_value(&ColumnMetadataKey::ParquetFieldId),
2577                            Some(MetadataValue::Number(4))
2578                        ));
2579                        assert!(matches!(
2580                            physical_field.get_config_value(&ColumnMetadataKey::ColumnMappingId),
2581                            Some(MetadataValue::Number(4))
2582                        ));
2583                    }
2584                    ColumnMappingMode::None => panic!("unexpected column mapping mode"),
2585                }
2586
2587                assert_eq!(
2588                    physical_field.name,
2589                    "col-5f422f40-de70-45b2-88ab-1d5c90e94db1"
2590                );
2591                let DataType::Array(atype) = physical_field.data_type else {
2592                    panic!("Expected an Array");
2593                };
2594                let DataType::Struct(stype) = atype.element_type else {
2595                    panic!("Expected a Struct");
2596                };
2597
2598                let struct_field = stype.fields.get_index(0).unwrap().1;
2599                assert_eq!(
2600                    struct_field.name,
2601                    "col-a7f4159c-53be-4cb0-b81a-f7e5240cfc49"
2602                );
2603
2604                // The subfield should also have ParquetFieldId present it column mapping id mode
2605                match mode {
2606                    ColumnMappingMode::Id => {
2607                        assert!(matches!(
2608                            struct_field.get_config_value(&ColumnMetadataKey::ParquetFieldId),
2609                            Some(MetadataValue::Number(5))
2610                        ));
2611                        assert!(matches!(
2612                            struct_field.get_config_value(&ColumnMetadataKey::ColumnMappingId),
2613                            Some(MetadataValue::Number(5))
2614                        ));
2615                    }
2616                    ColumnMappingMode::Name => {
2617                        assert!(matches!(
2618                            struct_field.get_config_value(&ColumnMetadataKey::ParquetFieldId),
2619                            Some(MetadataValue::Number(5))
2620                        ));
2621                        assert!(matches!(
2622                            struct_field.get_config_value(&ColumnMetadataKey::ColumnMappingId),
2623                            Some(MetadataValue::Number(5))
2624                        ));
2625                    }
2626                    ColumnMappingMode::None => panic!("unexpected column mapping mode"),
2627                }
2628            });
2629    }
2630
2631    #[test]
2632    fn test_make_physical_passes_metadata_column_through() {
2633        let field = StructField::create_metadata_column(
2634            "_metadata.row_index",
2635            MetadataColumnSpec::RowIndex,
2636        );
2637        for mode in [
2638            ColumnMappingMode::None,
2639            ColumnMappingMode::Name,
2640            ColumnMappingMode::Id,
2641        ] {
2642            let physical = field.make_physical(mode).unwrap();
2643            assert_eq!(physical.name(), "_metadata.row_index");
2644            assert!(physical.is_metadata_column());
2645        }
2646    }
2647
2648    #[test]
2649    fn test_make_physical_rejects_metadata_column_with_cm_annotations() {
2650        let field = StructField::create_metadata_column(
2651            "_metadata.row_index",
2652            MetadataColumnSpec::RowIndex,
2653        )
2654        .add_metadata([(
2655            ColumnMetadataKey::ColumnMappingPhysicalName.as_ref(),
2656            MetadataValue::String("phys".to_string()),
2657        )]);
2658        assert_result_error_with_message(
2659            field.make_physical(ColumnMappingMode::Name),
2660            "must not have column mapping annotations",
2661        );
2662    }
2663
2664    #[test]
2665    fn test_read_schemas() {
2666        let file = std::fs::File::open("./tests/serde/schema.json").unwrap();
2667        let schema: Result<Schema, _> = serde_json::from_reader(file);
2668        assert!(schema.is_ok());
2669
2670        let file = std::fs::File::open("./tests/serde/checkpoint_schema.json").unwrap();
2671        let schema: Result<Schema, _> = serde_json::from_reader(file);
2672        assert!(schema.is_ok())
2673    }
2674
2675    #[test]
2676    fn test_invalid_decimal() {
2677        let data = r#"
2678        {
2679            "name": "a",
2680            "type": "decimal(39, 10)",
2681            "nullable": false,
2682            "metadata": {}
2683        }
2684        "#;
2685        assert!(serde_json::from_str::<StructField>(data).is_err());
2686
2687        let data = r#"
2688        {
2689            "name": "a",
2690            "type": "decimal(10, 39)",
2691            "nullable": false,
2692            "metadata": {}
2693        }
2694        "#;
2695        assert!(serde_json::from_str::<StructField>(data).is_err());
2696    }
2697
2698    #[test]
2699    fn test_metadata_value_to_string() {
2700        assert_eq!(MetadataValue::Number(0).to_string(), "0");
2701        assert_eq!(
2702            MetadataValue::String("hello".to_string()).to_string(),
2703            "hello"
2704        );
2705        assert_eq!(MetadataValue::Boolean(true).to_string(), "true");
2706        assert_eq!(MetadataValue::Boolean(false).to_string(), "false");
2707        let object_json = serde_json::json!({ "an": "object" });
2708        assert_eq!(
2709            MetadataValue::Other(object_json).to_string(),
2710            "{\"an\":\"object\"}"
2711        );
2712        let array_json = serde_json::json!(["an", "array"]);
2713        assert_eq!(
2714            MetadataValue::Other(array_json).to_string(),
2715            "[\"an\",\"array\"]"
2716        );
2717    }
2718
2719    #[test]
2720    fn test_num_fields() {
2721        let schema = StructType::new_unchecked([]);
2722        assert!(schema.num_fields() == 0);
2723        let schema = StructType::new_unchecked([
2724            StructField::nullable("a", DataType::LONG),
2725            StructField::nullable("b", DataType::LONG),
2726            StructField::nullable("c", DataType::LONG),
2727            StructField::nullable("d", DataType::LONG),
2728        ]);
2729        assert_eq!(schema.num_fields(), 4);
2730        let schema = StructType::new_unchecked([
2731            StructField::nullable("b", DataType::LONG),
2732            StructField::not_null("b", DataType::LONG),
2733            StructField::nullable("c", DataType::LONG),
2734            StructField::nullable("c", DataType::LONG),
2735        ]);
2736        assert_eq!(schema.num_fields(), 2);
2737    }
2738
2739    #[test]
2740    fn test_has_invariants() {
2741        // Schema with no invariants
2742        let schema = StructType::new_unchecked([
2743            StructField::nullable("a", DataType::STRING),
2744            StructField::nullable("b", DataType::INTEGER),
2745        ]);
2746        assert!(!schema_has_invariants(&schema));
2747
2748        // Schema with top-level invariant
2749        let mut field = StructField::nullable("c", DataType::STRING);
2750        field.metadata.insert(
2751            ColumnMetadataKey::Invariants.as_ref().to_string(),
2752            MetadataValue::String("c > 0".to_string()),
2753        );
2754
2755        let schema =
2756            StructType::new_unchecked([StructField::nullable("a", DataType::STRING), field]);
2757        assert!(schema_has_invariants(&schema));
2758
2759        // Schema with nested invariant in a struct
2760        let nested_field = StructField::nullable(
2761            "nested_c",
2762            DataType::try_struct_type([{
2763                let mut field = StructField::nullable("d", DataType::INTEGER);
2764                field.metadata.insert(
2765                    ColumnMetadataKey::Invariants.as_ref().to_string(),
2766                    MetadataValue::String("d > 0".to_string()),
2767                );
2768                field
2769            }])
2770            .unwrap(),
2771        );
2772
2773        let schema = StructType::new_unchecked([
2774            StructField::nullable("a", DataType::STRING),
2775            StructField::nullable("b", DataType::INTEGER),
2776            nested_field,
2777        ]);
2778        assert!(schema_has_invariants(&schema));
2779
2780        // Schema with nested invariant in an array of structs
2781        let array_field = StructField::nullable(
2782            "array_field",
2783            ArrayType::new(
2784                DataType::try_struct_type([{
2785                    let mut field = StructField::nullable("d", DataType::INTEGER);
2786                    field.metadata.insert(
2787                        ColumnMetadataKey::Invariants.as_ref().to_string(),
2788                        MetadataValue::String("d > 0".to_string()),
2789                    );
2790                    field
2791                }])
2792                .unwrap(),
2793                true,
2794            ),
2795        );
2796
2797        let schema = StructType::new_unchecked([
2798            StructField::nullable("a", DataType::STRING),
2799            StructField::nullable("b", DataType::INTEGER),
2800            array_field,
2801        ]);
2802        assert!(schema_has_invariants(&schema));
2803
2804        // Schema with nested invariant in a map value that's a struct
2805        let map_field = StructField::nullable(
2806            "map_field",
2807            MapType::new(
2808                DataType::STRING,
2809                DataType::try_struct_type([{
2810                    let mut field = StructField::nullable("d", DataType::INTEGER);
2811                    field.metadata.insert(
2812                        ColumnMetadataKey::Invariants.as_ref().to_string(),
2813                        MetadataValue::String("d > 0".to_string()),
2814                    );
2815                    field
2816                }])
2817                .unwrap(),
2818                true,
2819            ),
2820        );
2821
2822        let schema = StructType::new_unchecked([
2823            StructField::nullable("a", DataType::STRING),
2824            StructField::nullable("b", DataType::INTEGER),
2825            map_field,
2826        ]);
2827        assert!(schema_has_invariants(&schema));
2828    }
2829
2830    fn all_nullable_schema() -> StructType {
2831        StructType::new_unchecked([
2832            StructField::nullable("a", DataType::STRING),
2833            StructField::nullable("b", DataType::INTEGER),
2834        ])
2835    }
2836
2837    fn top_level_non_null_schema() -> StructType {
2838        StructType::new_unchecked([
2839            StructField::not_null("id", DataType::INTEGER),
2840            StructField::nullable("name", DataType::STRING),
2841        ])
2842    }
2843
2844    fn nested_non_null_schema() -> StructType {
2845        let nested_field = StructField::nullable(
2846            "parent",
2847            DataType::try_struct_type([StructField::not_null("child", DataType::INTEGER)]).unwrap(),
2848        );
2849        StructType::new_unchecked([StructField::nullable("a", DataType::STRING), nested_field])
2850    }
2851
2852    fn array_non_null_schema() -> StructType {
2853        let array_field = StructField::nullable(
2854            "arr",
2855            ArrayType::new(
2856                DataType::try_struct_type([StructField::not_null("child", DataType::INTEGER)])
2857                    .unwrap(),
2858                true,
2859            ),
2860        );
2861        StructType::new_unchecked([array_field])
2862    }
2863
2864    fn map_non_null_schema() -> StructType {
2865        let map_field = StructField::nullable(
2866            "map",
2867            MapType::new(
2868                DataType::STRING,
2869                DataType::try_struct_type([StructField::not_null("child", DataType::INTEGER)])
2870                    .unwrap(),
2871                true,
2872            ),
2873        );
2874        StructType::new_unchecked([map_field])
2875    }
2876
2877    fn variant_only_schema() -> StructType {
2878        // Variant internal fields (metadata, value) are protocol-defined non-null but
2879        // must NOT be counted as user-controlled non-null fields.
2880        StructType::new_unchecked([StructField::nullable("v", DataType::unshredded_variant())])
2881    }
2882
2883    #[rstest]
2884    #[case::all_nullable(all_nullable_schema(), false)]
2885    #[case::top_level(top_level_non_null_schema(), true)]
2886    #[case::nested_struct(nested_non_null_schema(), true)]
2887    #[case::array_element(array_non_null_schema(), true)]
2888    #[case::map_value(map_non_null_schema(), true)]
2889    #[case::variant_skipped(variant_only_schema(), false)]
2890    fn test_schema_contains_non_null_fields(#[case] schema: StructType, #[case] expected: bool) {
2891        assert_eq!(schema_contains_non_null_fields(&schema), expected);
2892    }
2893
2894    #[test]
2895    fn test_struct_type_iterator_basic() {
2896        let fields = vec![
2897            StructField::new("field1", DataType::STRING, true),
2898            StructField::new("field2", DataType::INTEGER, false),
2899            StructField::new("field3", DataType::BOOLEAN, true),
2900        ];
2901        let struct_type = StructType::new_unchecked(fields.clone());
2902
2903        // Test fields() method returns reference iterator
2904        let field_names: Vec<_> = struct_type.fields().map(|f| f.name()).collect();
2905        assert_eq!(field_names, vec!["field1", "field2", "field3"]);
2906
2907        // Test that we can still access the struct_type after using fields()
2908        assert_eq!(struct_type.field("field1").unwrap().name, "field1");
2909    }
2910
2911    #[test]
2912    fn test_struct_type_into_iterator_owned() {
2913        let fields = vec![
2914            StructField::new("a", DataType::STRING, true),
2915            StructField::new("b", DataType::INTEGER, false),
2916        ];
2917        let struct_type = StructType::new_unchecked(fields);
2918
2919        // Test owned iteration (consumes the struct)
2920        let mut field_names = Vec::new();
2921        for field in struct_type {
2922            field_names.push(field.name);
2923        }
2924        assert_eq!(field_names, vec!["a", "b"]);
2925    }
2926
2927    #[test]
2928    fn test_struct_type_into_iterator_references() {
2929        let fields = vec![
2930            StructField::new("x", DataType::DOUBLE, true),
2931            StructField::new("y", DataType::FLOAT, false),
2932            StructField::new("z", DataType::LONG, true),
2933        ];
2934        let struct_type = StructType::new_unchecked(fields);
2935
2936        // Test reference iteration (does not consume the struct)
2937        let mut field_names = Vec::new();
2938        for field in &struct_type {
2939            field_names.push(field.name().clone());
2940        }
2941        assert_eq!(field_names, vec!["x", "y", "z"]);
2942
2943        // Should still be able to use struct_type after iteration
2944        assert_eq!(struct_type.field("x").unwrap().name, "x");
2945    }
2946
2947    #[test]
2948    fn test_iterator_exact_size() {
2949        let fields = vec![
2950            StructField::new("field1", DataType::STRING, true),
2951            StructField::new("field2", DataType::INTEGER, false),
2952            StructField::new("field3", DataType::BOOLEAN, true),
2953            StructField::new("field4", DataType::DATE, true),
2954        ];
2955
2956        // Test ExactSizeIterator for reference iterator
2957        let struct_type = StructType::new_unchecked(fields.clone());
2958        let ref_iter = struct_type.fields();
2959        assert_eq!(ref_iter.len(), 4);
2960
2961        // Test ExactSizeIterator for &StructType into_iter
2962        let struct_type = StructType::new_unchecked(fields.clone());
2963        let into_ref_iter = (&struct_type).into_iter();
2964        assert_eq!(into_ref_iter.len(), 4);
2965
2966        // Test ExactSizeIterator for StructType into_iter (consuming)
2967        let struct_type = StructType::new_unchecked(fields);
2968        let into_owned_iter = struct_type.into_iter();
2969        assert_eq!(into_owned_iter.len(), 4);
2970    }
2971
2972    #[test]
2973    fn test_iterator_with_metadata() {
2974        let field_with_metadata = StructField::new("test_field", DataType::STRING, true)
2975            .with_metadata([("key1", MetadataValue::String("value1".to_string()))]);
2976
2977        let struct_type = StructType::new_unchecked([field_with_metadata]);
2978
2979        // Test that metadata is preserved through iteration
2980        for field in &struct_type {
2981            assert_eq!(field.metadata().len(), 1);
2982            assert_eq!(
2983                field.metadata().get("key1"),
2984                Some(&MetadataValue::String("value1".to_string()))
2985            );
2986        }
2987
2988        // Test consuming iterator preserves metadata
2989        for field in struct_type {
2990            assert_eq!(field.metadata().len(), 1);
2991            assert_eq!(
2992                field.metadata().get("key1"),
2993                Some(&MetadataValue::String("value1".to_string()))
2994            );
2995        }
2996    }
2997
2998    #[test]
2999    fn test_empty_struct_type_iterator() {
3000        let struct_type = StructType::new_unchecked(std::iter::empty::<StructField>());
3001
3002        // Test all iterator methods with empty struct
3003        assert_eq!(struct_type.fields().count(), 0);
3004        assert_eq!((&struct_type).into_iter().count(), 0);
3005        assert_eq!(struct_type.into_iter().count(), 0);
3006    }
3007
3008    #[test]
3009    fn test_iterator_order_preservation() {
3010        let fields = vec![
3011            StructField::new("zebra", DataType::STRING, true),
3012            StructField::new("apple", DataType::INTEGER, false),
3013            StructField::new("banana", DataType::BOOLEAN, true),
3014        ];
3015        let struct_type = StructType::new_unchecked(fields);
3016
3017        // IndexMap should preserve insertion order
3018        let field_names: Vec<_> = struct_type.fields().map(|f| f.name()).collect();
3019        assert_eq!(field_names, vec!["zebra", "apple", "banana"]);
3020
3021        // Order should be the same across different iterator methods
3022        let ref_names: Vec<_> = (&struct_type).into_iter().map(|f| f.name()).collect();
3023        assert_eq!(ref_names, vec!["zebra", "apple", "banana"]);
3024
3025        // Test consuming iterator maintains order too
3026        let owned_names: Vec<_> = struct_type.into_iter().map(|f| f.name).collect();
3027        assert_eq!(owned_names, vec!["zebra", "apple", "banana"]);
3028    }
3029
3030    #[test]
3031    fn test_iterator_collect() {
3032        let original_fields = vec![
3033            StructField::new("field1", DataType::STRING, true),
3034            StructField::new("field2", DataType::INTEGER, false),
3035        ];
3036        let struct_type = StructType::new_unchecked(original_fields.clone());
3037
3038        // Test collecting from reference iterator
3039        let collected_refs: Vec<&StructField> = struct_type.fields().collect();
3040        assert_eq!(collected_refs.len(), 2);
3041        assert_eq!(collected_refs[0].name, "field1");
3042        assert_eq!(collected_refs[1].name, "field2");
3043
3044        // Test collecting from consuming iterator
3045        let collected_owned: Vec<StructField> = struct_type.into_iter().collect();
3046        assert_eq!(collected_owned.len(), 2);
3047        assert_eq!(collected_owned[0].name, "field1");
3048        assert_eq!(collected_owned[1].name, "field2");
3049    }
3050
3051    #[test]
3052    fn test_iterator_functional_methods() {
3053        let fields = vec![
3054            StructField::new("nullable_string", DataType::STRING, true),
3055            StructField::new("required_int", DataType::INTEGER, false),
3056            StructField::new("nullable_bool", DataType::BOOLEAN, true),
3057            StructField::new("required_long", DataType::LONG, false),
3058        ];
3059        let struct_type = StructType::new_unchecked(fields);
3060
3061        // Test filter - find nullable fields
3062        let nullable_count = struct_type.fields().filter(|f| f.is_nullable()).count();
3063        assert_eq!(nullable_count, 2);
3064
3065        // Test map and filter chain
3066        let required_field_names: Vec<_> = struct_type
3067            .fields()
3068            .filter(|f| !f.is_nullable())
3069            .map(|f| f.name())
3070            .collect();
3071        assert_eq!(required_field_names, vec!["required_int", "required_long"]);
3072
3073        // Test enumerate
3074        for (index, field) in struct_type.fields().enumerate() {
3075            match index {
3076                0 => assert_eq!(field.name, "nullable_string"),
3077                1 => assert_eq!(field.name, "required_int"),
3078                2 => assert_eq!(field.name, "nullable_bool"),
3079                3 => assert_eq!(field.name, "required_long"),
3080                _ => panic!("Unexpected field index: {index}"),
3081            }
3082        }
3083    }
3084
3085    #[test]
3086    fn test_double_ended_iterator_ref() {
3087        let fields = vec![
3088            StructField::new("first", DataType::STRING, true),
3089            StructField::new("second", DataType::INTEGER, false),
3090            StructField::new("third", DataType::BOOLEAN, true),
3091            StructField::new("fourth", DataType::LONG, false),
3092        ];
3093        let struct_type = StructType::new_unchecked(fields);
3094
3095        // Test iterating from both ends using reference iterator
3096        let mut iter = struct_type.fields();
3097
3098        // Forward iteration
3099        assert_eq!(iter.next().unwrap().name, "first");
3100        assert_eq!(iter.next().unwrap().name, "second");
3101
3102        // Backward iteration
3103        assert_eq!(iter.next_back().unwrap().name, "fourth");
3104        assert_eq!(iter.next_back().unwrap().name, "third");
3105
3106        // Should be exhausted
3107        assert!(iter.next().is_none());
3108        assert!(iter.next_back().is_none());
3109    }
3110
3111    #[test]
3112    fn test_double_ended_iterator_owned() {
3113        let fields = vec![
3114            StructField::new("alpha", DataType::STRING, true),
3115            StructField::new("beta", DataType::INTEGER, false),
3116            StructField::new("gamma", DataType::BOOLEAN, true),
3117        ];
3118        let struct_type = StructType::new_unchecked(fields);
3119
3120        // Test iterating from both ends using owned iterator
3121        let mut iter = struct_type.into_iter();
3122
3123        // Backward iteration first
3124        assert_eq!(iter.next_back().unwrap().name, "gamma");
3125
3126        // Forward iteration
3127        assert_eq!(iter.next().unwrap().name, "alpha");
3128
3129        // Backward iteration again
3130        assert_eq!(iter.next_back().unwrap().name, "beta");
3131
3132        // Should be exhausted
3133        assert!(iter.next().is_none());
3134        assert!(iter.next_back().is_none());
3135    }
3136
3137    #[test]
3138    fn test_double_ended_iterator_collect_reverse() {
3139        let fields = vec![
3140            StructField::new("one", DataType::STRING, true),
3141            StructField::new("two", DataType::INTEGER, false),
3142            StructField::new("three", DataType::BOOLEAN, true),
3143        ];
3144        let struct_type = StructType::new_unchecked(fields);
3145
3146        // Test collecting in reverse order using DoubleEndedIterator
3147        let reversed_names: Vec<_> = struct_type.fields().rev().map(|f| f.name()).collect();
3148        assert_eq!(reversed_names, vec!["three", "two", "one"]);
3149
3150        // Test that we can still use the original struct
3151        assert_eq!(struct_type.field("two").unwrap().name, "two");
3152    }
3153
3154    #[test]
3155    fn test_double_ended_iterator_with_into_iter_ref() {
3156        let fields = vec![
3157            StructField::new("x", DataType::DOUBLE, true),
3158            StructField::new("y", DataType::FLOAT, false),
3159            StructField::new("z", DataType::LONG, true),
3160        ];
3161        let struct_type = StructType::new_unchecked(fields);
3162
3163        // Test DoubleEndedIterator with &StructType into_iter
3164        let mut iter = (&struct_type).into_iter();
3165
3166        // Mix forward and backward iteration
3167        assert_eq!(iter.next().unwrap().name, "x");
3168        assert_eq!(iter.next_back().unwrap().name, "z");
3169        assert_eq!(iter.next().unwrap().name, "y");
3170
3171        // Should be exhausted
3172        assert!(iter.next().is_none());
3173        assert!(iter.next_back().is_none());
3174    }
3175
3176    #[test]
3177    fn test_fused_iterator_ref() {
3178        let fields = vec![
3179            StructField::new("test1", DataType::STRING, true),
3180            StructField::new("test2", DataType::INTEGER, false),
3181        ];
3182        let struct_type = StructType::new_unchecked(fields);
3183
3184        // Verify that reference iterator implements FusedIterator
3185        let mut iter = struct_type.fields();
3186
3187        // Exhaust the iterator
3188        assert!(iter.next().is_some());
3189        assert!(iter.next().is_some());
3190        assert!(iter.next().is_none());
3191
3192        // FusedIterator guarantees that calling next() after exhaustion always returns None
3193        assert!(iter.next().is_none());
3194        assert!(iter.next().is_none());
3195        assert!(iter.next().is_none());
3196    }
3197
3198    #[test]
3199    fn test_fused_iterator_owned() {
3200        let fields = vec![
3201            StructField::new("item1", DataType::STRING, true),
3202            StructField::new("item2", DataType::INTEGER, false),
3203        ];
3204        let struct_type = StructType::new_unchecked(fields);
3205
3206        // Verify that owned iterator implements FusedIterator
3207        let mut iter = struct_type.into_iter();
3208
3209        // Exhaust the iterator
3210        assert!(iter.next().is_some());
3211        assert!(iter.next().is_some());
3212        assert!(iter.next().is_none());
3213
3214        // FusedIterator guarantees that calling next() after exhaustion always returns None
3215        assert!(iter.next().is_none());
3216        assert!(iter.next().is_none());
3217        assert!(iter.next().is_none());
3218    }
3219
3220    #[test]
3221    fn test_fused_iterator_with_into_iter_ref() {
3222        let fields = vec![StructField::new("field_a", DataType::BOOLEAN, true)];
3223        let struct_type = StructType::new_unchecked(fields);
3224
3225        // Verify that &StructType into_iter implements FusedIterator
3226        let mut iter = (&struct_type).into_iter();
3227
3228        // Exhaust the iterator
3229        assert!(iter.next().is_some());
3230        assert!(iter.next().is_none());
3231
3232        // FusedIterator guarantees that calling next() after exhaustion always returns None
3233        assert!(iter.next().is_none());
3234        assert!(iter.next().is_none());
3235    }
3236
3237    #[test]
3238    fn test_fused_double_ended_iterator_empty() {
3239        let struct_type = StructType::new_unchecked(std::iter::empty::<StructField>());
3240
3241        // Test both forward and backward iteration on empty iterator
3242        let mut iter = struct_type.fields();
3243
3244        // Empty iterator should return None immediately
3245        assert!(iter.next().is_none());
3246        assert!(iter.next_back().is_none());
3247
3248        // FusedIterator guarantees continued None after exhaustion
3249        assert!(iter.next().is_none());
3250        assert!(iter.next_back().is_none());
3251    }
3252
3253    #[test]
3254    fn test_double_ended_iterator_single_element() {
3255        let fields = vec![StructField::new("single", DataType::STRING, true)];
3256        let struct_type = StructType::new_unchecked(fields);
3257
3258        // Test DoubleEndedIterator with single element
3259        let mut iter = struct_type.fields();
3260
3261        // Should get the single element from next()
3262        assert_eq!(iter.next().unwrap().name, "single");
3263        assert!(iter.next().is_none());
3264        assert!(iter.next_back().is_none());
3265
3266        // Test getting single element from next_back()
3267        let struct_type =
3268            StructType::new_unchecked([StructField::new("single2", DataType::INTEGER, false)]);
3269        let mut iter = struct_type.into_iter();
3270
3271        assert_eq!(iter.next_back().unwrap().name, "single2");
3272        assert!(iter.next().is_none());
3273        assert!(iter.next_back().is_none());
3274    }
3275
3276    #[test]
3277    fn test_metadata_column_spec() -> DeltaResult<()> {
3278        // Test text_value
3279        assert_eq!(MetadataColumnSpec::RowIndex.text_value(), "row_index");
3280        assert_eq!(MetadataColumnSpec::RowId.text_value(), "row_id");
3281        assert_eq!(
3282            MetadataColumnSpec::RowCommitVersion.text_value(),
3283            "row_commit_version"
3284        );
3285        assert_eq!(MetadataColumnSpec::FilePath.text_value(), "_file");
3286
3287        // Test data_type
3288        assert_eq!(MetadataColumnSpec::RowIndex.data_type(), DataType::LONG);
3289        assert_eq!(MetadataColumnSpec::RowId.data_type(), DataType::LONG);
3290        assert_eq!(
3291            MetadataColumnSpec::RowCommitVersion.data_type(),
3292            DataType::LONG
3293        );
3294        assert_eq!(MetadataColumnSpec::FilePath.data_type(), DataType::STRING);
3295
3296        // Test nullable
3297        assert!(!MetadataColumnSpec::RowIndex.nullable());
3298        assert!(!MetadataColumnSpec::RowId.nullable());
3299        assert!(!MetadataColumnSpec::RowCommitVersion.nullable());
3300        assert!(!MetadataColumnSpec::FilePath.nullable());
3301
3302        // Test reserved_field_id
3303        assert_eq!(MetadataColumnSpec::RowIndex.reserved_field_id(), None);
3304        assert_eq!(MetadataColumnSpec::RowId.reserved_field_id(), None);
3305        assert_eq!(
3306            MetadataColumnSpec::RowCommitVersion.reserved_field_id(),
3307            None
3308        );
3309        assert_eq!(
3310            MetadataColumnSpec::FilePath.reserved_field_id(),
3311            Some(crate::reserved_field_ids::FILE_NAME)
3312        );
3313
3314        // Test from_str
3315        assert_eq!(
3316            MetadataColumnSpec::from_str("row_index")?,
3317            MetadataColumnSpec::RowIndex
3318        );
3319        assert_eq!(
3320            MetadataColumnSpec::from_str("row_id")?,
3321            MetadataColumnSpec::RowId
3322        );
3323        assert_eq!(
3324            MetadataColumnSpec::from_str("row_commit_version")?,
3325            MetadataColumnSpec::RowCommitVersion
3326        );
3327        assert_eq!(
3328            MetadataColumnSpec::from_str("_file")?,
3329            MetadataColumnSpec::FilePath
3330        );
3331
3332        // Test invalid from_str
3333        assert!(MetadataColumnSpec::from_str("invalid").is_err());
3334
3335        Ok(())
3336    }
3337
3338    #[test]
3339    fn test_create_metadata_column() {
3340        let field =
3341            StructField::create_metadata_column("test_row_index", MetadataColumnSpec::RowIndex);
3342
3343        assert_eq!(field.name(), "test_row_index");
3344        assert_eq!(field.data_type(), &DataType::LONG);
3345        assert!(!field.nullable);
3346        assert!(field.is_metadata_column());
3347        assert_eq!(
3348            field.get_metadata_column_spec(),
3349            Some(MetadataColumnSpec::RowIndex)
3350        );
3351    }
3352
3353    #[test]
3354    fn test_default_row_index_column() {
3355        let field = StructField::default_row_index_column();
3356
3357        assert_eq!(field.name(), "_metadata.row_index");
3358        assert_eq!(field.data_type(), &DataType::LONG);
3359        assert!(!field.nullable);
3360        assert!(field.is_metadata_column());
3361        assert_eq!(
3362            field.get_metadata_column_spec(),
3363            Some(MetadataColumnSpec::RowIndex)
3364        );
3365    }
3366
3367    #[test]
3368    fn test_add_column() -> DeltaResult<()> {
3369        let schema = StructType::try_new([StructField::nullable("col1", DataType::STRING)])?;
3370
3371        let new_field = StructField::nullable("col2", DataType::INTEGER);
3372        let updated_schema = schema.add([new_field])?;
3373
3374        assert_eq!(updated_schema.fields().count(), 2);
3375        assert!(updated_schema.contains("col1"));
3376        assert!(updated_schema.contains("col2"));
3377        Ok(())
3378    }
3379
3380    #[test]
3381    fn test_add_metadata_column() -> DeltaResult<()> {
3382        let schema = StructType::try_new([StructField::nullable("regular_col", DataType::STRING)])?;
3383
3384        let schema_with_metadata =
3385            schema.add_metadata_column("my_row_index", MetadataColumnSpec::RowIndex)?;
3386
3387        assert_eq!(schema_with_metadata.fields().count(), 2);
3388        assert!(schema_with_metadata.contains_metadata_column(&MetadataColumnSpec::RowIndex));
3389        assert!(schema_with_metadata.contains("my_row_index"));
3390        assert_eq!(
3391            schema_with_metadata.index_of_metadata_column(&MetadataColumnSpec::RowIndex),
3392            Some(&1)
3393        );
3394        Ok(())
3395    }
3396
3397    #[test]
3398    fn test_duplicate_metadata_columns() -> DeltaResult<()> {
3399        let schema = StructType::try_new([StructField::nullable("regular_col", DataType::STRING)])?;
3400
3401        let schema_with_metadata =
3402            schema.add_metadata_column("row_index1", MetadataColumnSpec::RowIndex)?;
3403
3404        // Adding another row index metadata column should fail
3405        let result =
3406            schema_with_metadata.add_metadata_column("row_index2", MetadataColumnSpec::RowIndex);
3407
3408        assert_result_error_with_message(result, "Duplicate metadata column");
3409        Ok(())
3410    }
3411
3412    #[test]
3413    fn test_duplicate_field_name_case_insensitive() {
3414        // Delta column names are case-insensitive per protocol; (Value, value) is invalid
3415        let result = StructType::try_new([
3416            StructField::nullable("Value", DataType::INTEGER),
3417            StructField::nullable("value", DataType::STRING),
3418        ]);
3419        assert_result_error_with_message(result, "Duplicate field name (case-insensitive)");
3420    }
3421
3422    #[test]
3423    fn test_duplicate_field_name_exact() {
3424        // Exact duplicate (same name twice) is rejected via the case-insensitive check
3425        let result = StructType::try_new([
3426            StructField::nullable("id", DataType::INTEGER),
3427            StructField::nullable("id", DataType::STRING),
3428        ]);
3429        assert_result_error_with_message(result, "Duplicate field name (case-insensitive)");
3430    }
3431
3432    #[test]
3433    fn test_nested_metadata_columns_validation_struct() -> DeltaResult<()> {
3434        // Test that metadata columns in nested structs are rejected
3435        let nested_field_with_metadata =
3436            StructField::create_metadata_column("nested_row_index", MetadataColumnSpec::RowIndex);
3437        let nested_struct = StructType {
3438            type_name: "struct".into(),
3439            fields: [(
3440                nested_field_with_metadata.name.clone(),
3441                nested_field_with_metadata,
3442            )]
3443            .into_iter()
3444            .collect(),
3445            metadata_columns: HashMap::new(),
3446        };
3447
3448        let result = StructType::try_new([
3449            StructField::nullable("regular_col", DataType::STRING),
3450            StructField::nullable("nested", DataType::Struct(Box::new(nested_struct))),
3451        ]);
3452
3453        assert_result_error_with_message(result, "only allowed at the top level");
3454        Ok(())
3455    }
3456
3457    #[test]
3458    fn test_nested_metadata_columns_validation_array() -> DeltaResult<()> {
3459        // Test that metadata columns in array element structs are rejected
3460        let nested_field_with_metadata =
3461            StructField::create_metadata_column("nested_row_index", MetadataColumnSpec::RowIndex);
3462        let nested_struct = StructType {
3463            type_name: "struct".into(),
3464            fields: [(
3465                nested_field_with_metadata.name.clone(),
3466                nested_field_with_metadata,
3467            )]
3468            .into_iter()
3469            .collect(),
3470            metadata_columns: HashMap::new(),
3471        };
3472        let array_type = ArrayType::new(DataType::Struct(Box::new(nested_struct)), true);
3473
3474        let result = StructType::try_new([
3475            StructField::nullable("regular_col", DataType::STRING),
3476            StructField::nullable("array_col", DataType::Array(Box::new(array_type))),
3477        ]);
3478
3479        assert_result_error_with_message(result, "only allowed at the top level");
3480        Ok(())
3481    }
3482
3483    #[test]
3484    fn test_nested_metadata_columns_validation_map() -> DeltaResult<()> {
3485        // Test that metadata columns in map key structs or map value structs are rejected
3486        let nested_field_with_metadata =
3487            StructField::create_metadata_column("nested_row_index", MetadataColumnSpec::RowIndex);
3488        let nested_struct = StructType {
3489            type_name: "struct".into(),
3490            fields: [(
3491                nested_field_with_metadata.name.clone(),
3492                nested_field_with_metadata,
3493            )]
3494            .into_iter()
3495            .collect(),
3496            metadata_columns: HashMap::new(),
3497        };
3498
3499        for map_type in [
3500            MapType::new(
3501                DataType::Struct(Box::new(nested_struct.clone())),
3502                DataType::STRING,
3503                true,
3504            ),
3505            MapType::new(
3506                DataType::STRING,
3507                DataType::Struct(Box::new(nested_struct)),
3508                true,
3509            ),
3510        ] {
3511            let result = StructType::try_new([
3512                StructField::nullable("regular_col", DataType::STRING),
3513                StructField::nullable("map_col", DataType::Map(Box::new(map_type))),
3514            ]);
3515
3516            assert_result_error_with_message(result, "only allowed at the top level");
3517        }
3518
3519        Ok(())
3520    }
3521
3522    #[test]
3523    fn test_column_identifier_trait() -> DeltaResult<()> {
3524        let schema = StructType::try_new([
3525            StructField::nullable("regular_col", DataType::STRING),
3526            StructField::create_metadata_column("row_index_col", MetadataColumnSpec::RowIndex),
3527        ])?;
3528
3529        // Test string identifier
3530        assert!(schema.contains("regular_col"));
3531        assert!(schema.contains("row_index_col"));
3532        assert!(!schema.contains("nonexistent"));
3533
3534        // Test String identifier
3535        assert!(schema.contains("regular_col"));
3536        assert!(schema.contains("row_index_col"));
3537
3538        // Test MetadataColumnSpec identifier
3539        assert!(schema.contains_metadata_column(&MetadataColumnSpec::RowIndex));
3540        assert!(!schema.contains_metadata_column(&MetadataColumnSpec::RowId));
3541        Ok(())
3542    }
3543
3544    #[test]
3545    fn test_metadata_column_serialization() -> DeltaResult<()> {
3546        let field = StructField::create_metadata_column("test_row_id", MetadataColumnSpec::RowId);
3547
3548        // Test that serialization works
3549        let json = serde_json::to_string(&field)?;
3550        let deserialized: StructField = serde_json::from_str(&json)?;
3551
3552        assert_eq!(deserialized.name(), field.name());
3553        assert_eq!(deserialized.data_type(), field.data_type());
3554        assert_eq!(deserialized.nullable, field.nullable);
3555        assert!(deserialized.is_metadata_column());
3556        assert_eq!(
3557            deserialized.get_metadata_column_spec(),
3558            Some(MetadataColumnSpec::RowId)
3559        );
3560        Ok(())
3561    }
3562
3563    #[test]
3564    fn test_all_metadata_column_specs() -> DeltaResult<()> {
3565        let schema = StructType::try_new([StructField::nullable("regular_col", DataType::STRING)])?;
3566
3567        let schema = schema
3568            .add_metadata_column("row_index", MetadataColumnSpec::RowIndex)?
3569            .add_metadata_column("row_id", MetadataColumnSpec::RowId)?
3570            .add_metadata_column("row_commit_version", MetadataColumnSpec::RowCommitVersion)?;
3571
3572        assert_eq!(schema.fields().count(), 4);
3573        assert!(schema.contains_metadata_column(&MetadataColumnSpec::RowIndex));
3574        assert!(schema.contains_metadata_column(&MetadataColumnSpec::RowId));
3575        assert!(schema.contains_metadata_column(&MetadataColumnSpec::RowCommitVersion));
3576
3577        assert_eq!(
3578            schema.index_of_metadata_column(&MetadataColumnSpec::RowIndex),
3579            Some(&1)
3580        );
3581        assert_eq!(
3582            schema.index_of_metadata_column(&MetadataColumnSpec::RowId),
3583            Some(&2)
3584        );
3585        assert_eq!(
3586            schema.index_of_metadata_column(&MetadataColumnSpec::RowCommitVersion),
3587            Some(&3)
3588        );
3589        Ok(())
3590    }
3591
3592    #[test]
3593    fn test_physical_name_with_mode_none() {
3594        let field_json = r#"{
3595            "name": "logical_name",
3596            "type": "string",
3597            "nullable": true,
3598            "metadata": {
3599                "delta.columnMapping.physicalName": "physical_name_col123"
3600            }
3601        }"#;
3602        let field: StructField = serde_json::from_str(field_json).unwrap();
3603
3604        // With ColumnMappingMode::None, should return logical name even though physical name exists
3605        assert_eq!(field.physical_name(ColumnMappingMode::None), "logical_name");
3606    }
3607
3608    #[test]
3609    fn test_physical_name_with_mode_id() {
3610        let field_json = r#"{
3611            "name": "logical_name",
3612            "type": "string",
3613            "nullable": true,
3614            "metadata": {
3615                "delta.columnMapping.id": 5,
3616                "delta.columnMapping.physicalName": "physical_name_col123"
3617            }
3618        }"#;
3619        let field: StructField = serde_json::from_str(field_json).unwrap();
3620
3621        // With ColumnMappingMode::Id, should return physical name
3622        assert_eq!(
3623            field.physical_name(ColumnMappingMode::Id),
3624            "physical_name_col123"
3625        );
3626    }
3627
3628    #[test]
3629    fn test_physical_name_with_mode_name() {
3630        let field_json = r#"{
3631            "name": "logical_name",
3632            "type": "string",
3633            "nullable": true,
3634            "metadata": {
3635                "delta.columnMapping.physicalName": "physical_name_col456"
3636            }
3637        }"#;
3638        let field: StructField = serde_json::from_str(field_json).unwrap();
3639
3640        // With ColumnMappingMode::Name, should return physical name
3641        assert_eq!(
3642            field.physical_name(ColumnMappingMode::Name),
3643            "physical_name_col456"
3644        );
3645    }
3646
3647    #[test]
3648    fn test_physical_name_fallback_id() {
3649        let field_json = r#"{
3650            "name": "logical_name",
3651            "type": "string",
3652            "nullable": true,
3653            "metadata": {}
3654        }"#;
3655        let field: StructField = serde_json::from_str(field_json).unwrap();
3656
3657        // With ColumnMappingMode::Id but no physical name, should fallback to logical name
3658        assert_eq!(field.physical_name(ColumnMappingMode::Id), "logical_name");
3659    }
3660
3661    #[test]
3662    fn test_physical_name_fallback_name() {
3663        let field_json = r#"{
3664            "name": "logical_name",
3665            "type": "string",
3666            "nullable": true,
3667            "metadata": {}
3668        }"#;
3669        let field: StructField = serde_json::from_str(field_json).unwrap();
3670
3671        // With ColumnMappingMode::Name but no physical name, should fallback to logical name
3672        assert_eq!(field.physical_name(ColumnMappingMode::Name), "logical_name");
3673    }
3674
3675    #[test]
3676    fn test_display_struct_type_stable_output() -> DeltaResult<()> {
3677        let nested_field_with_metadata =
3678            StructField::create_metadata_column("nested_row_index", MetadataColumnSpec::RowIndex);
3679        let inner_struct =
3680            StructType::new_unchecked([StructField::new("q", DataType::LONG, false)]);
3681        let nested_struct = StructType::new_unchecked([
3682            nested_field_with_metadata,
3683            StructField::new("x", DataType::DOUBLE, true),
3684            StructField::new(
3685                "inner_struct",
3686                DataType::Struct(Box::new(inner_struct)),
3687                false,
3688            ),
3689        ]);
3690        let array_type = ArrayType::new(DataType::Struct(Box::new(nested_struct.clone())), true);
3691        let map_type = MapType::new(
3692            DataType::Struct(Box::new(nested_struct.clone())),
3693            DataType::Struct(Box::new(nested_struct.clone())), // kek
3694            true,
3695        );
3696        let fields = vec![
3697            StructField::new("x", DataType::DOUBLE, true),
3698            StructField::new("y", DataType::FLOAT, false),
3699            StructField::new("z", DataType::LONG, true),
3700            StructField::new("s", nested_struct.clone(), false),
3701            StructField::nullable("array_col", DataType::Array(Box::new(array_type))),
3702            StructField::nullable("map_col", DataType::Map(Box::new(map_type))),
3703            StructField::new("a", DataType::LONG, true),
3704        ];
3705
3706        let struct_type = StructType::new_unchecked(fields);
3707        assert_eq!(
3708            struct_type.to_string(),
3709            "struct:
3710├─x: double (is nullable: true, metadata: {})
3711├─y: float (is nullable: false, metadata: {})
3712├─z: long (is nullable: true, metadata: {})
3713├─s: struct<nested_row_index: long, x: double, inner_struct: struct<q: long>> (is nullable: false, metadata: {})
3714│  ├─nested_row_index: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_index\")})
3715│  ├─x: double (is nullable: true, metadata: {})
3716│  └─inner_struct: struct<q: long> (is nullable: false, metadata: {})
3717│     └─q: long (is nullable: false, metadata: {})
3718├─array_col: array<struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>> (is nullable: true, metadata: {})
3719│  └─array_element: struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>
3720│     ├─nested_row_index: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_index\")})
3721│     ├─x: double (is nullable: true, metadata: {})
3722│     └─inner_struct: struct<q: long> (is nullable: false, metadata: {})
3723│        └─q: long (is nullable: false, metadata: {})
3724├─map_col: map<struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>, struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>> (is nullable: true, metadata: {})
3725│  ├─map_key: struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>
3726│  │  ├─nested_row_index: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_index\")})
3727│  │  ├─x: double (is nullable: true, metadata: {})
3728│  │  └─inner_struct: struct<q: long> (is nullable: false, metadata: {})
3729│  │     └─q: long (is nullable: false, metadata: {})
3730│  └─map_value: struct<nested_row_index: long, x: double, inner_struct: struct<q: long>>
3731│     ├─nested_row_index: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_index\")})
3732│     ├─x: double (is nullable: true, metadata: {})
3733│     └─inner_struct: struct<q: long> (is nullable: false, metadata: {})
3734│        └─q: long (is nullable: false, metadata: {})
3735└─a: long (is nullable: true, metadata: {})
3736"
3737        );
3738
3739        let schema = StructType::try_new([StructField::nullable("regular_col", DataType::STRING)])?;
3740        let schema = schema
3741            .add_metadata_column("row_index", MetadataColumnSpec::RowIndex)?
3742            .add_metadata_column("row_id", MetadataColumnSpec::RowId)?
3743            .add_metadata_column("row_commit_version", MetadataColumnSpec::RowCommitVersion)?;
3744        assert_eq!(schema.to_string(), "struct:
3745├─regular_col: string (is nullable: true, metadata: {})
3746├─row_index: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_index\")})
3747├─row_id: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_id\")})
3748└─row_commit_version: long (is nullable: false, metadata: {delta.metadataSpec: String(\"row_commit_version\")})
3749");
3750        Ok(())
3751    }
3752
3753    #[test]
3754    fn test_builder_empty() {
3755        let schema = StructType::builder().build().unwrap();
3756        assert_eq!(schema.num_fields(), 0)
3757    }
3758
3759    #[test]
3760    fn test_builder_add_fields() {
3761        let schema = StructType::builder()
3762            .add_field(StructField::new("id", DataType::INTEGER, false))
3763            .add_field(StructField::new("name", DataType::STRING, true))
3764            .build()
3765            .unwrap();
3766
3767        assert_eq!(schema.num_fields(), 2);
3768        assert_eq!(schema.field_at_index(0).unwrap().name(), "id");
3769        assert_eq!(schema.field_at_index(1).unwrap().name(), "name");
3770    }
3771
3772    #[test]
3773    fn test_builder_from_schema() {
3774        let base_schema =
3775            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3776
3777        let extended_schema = StructTypeBuilder::from_schema(&base_schema)
3778            .add_field(StructField::new("name", DataType::STRING, true))
3779            .build()
3780            .unwrap();
3781
3782        assert_eq!(extended_schema.num_fields(), 2);
3783        assert_eq!(extended_schema.field_at_index(0).unwrap().name(), "id");
3784        assert_eq!(extended_schema.field_at_index(1).unwrap().name(), "name");
3785    }
3786
3787    #[test]
3788    fn test_parquet_field_id_key_value() {
3789        // Verify the string value of ColumnMetadataKey::ParquetFieldId matches the convention
3790        // used by delta-spark and other Delta ecosystem implementations. This is not part of
3791        // the Delta protocol spec, so we pin the value here to catch accidental changes.
3792        assert_eq!(
3793            ColumnMetadataKey::ParquetFieldId.as_ref(),
3794            "parquet.field.id"
3795        );
3796    }
3797
3798    #[test]
3799    fn test_with_field_inserted_empty_struct() {
3800        let schema = StructType::try_new([]).unwrap();
3801        let schema = schema
3802            .with_field_inserted_after(None, StructField::new("age", DataType::STRING, true))
3803            .expect("with field inserted should produce a valid schema");
3804        assert_eq!(schema.num_fields(), 1);
3805        assert_eq!(schema.field_at_index(0).unwrap().name(), "age");
3806    }
3807
3808    #[test]
3809    fn test_with_field_inserted() {
3810        let schema = StructType::try_new([
3811            StructField::new("id", DataType::INTEGER, false),
3812            StructField::new("name", DataType::STRING, true),
3813        ])
3814        .unwrap();
3815        let schema = schema
3816            .with_field_inserted_after(Some("id"), StructField::new("age", DataType::STRING, true))
3817            .expect("with field inserted should produce a valid schema");
3818        assert_eq!(schema.num_fields(), 3);
3819        assert_eq!(schema.field_at_index(0).unwrap().name(), "id");
3820        assert_eq!(schema.field_at_index(1).unwrap().name(), "age");
3821        assert_eq!(schema.field_at_index(2).unwrap().name(), "name");
3822    }
3823
3824    #[test]
3825    fn test_with_field_inserted_append_to_end() {
3826        let schema = StructType::try_new([
3827            StructField::new("id", DataType::INTEGER, false),
3828            StructField::new("name", DataType::STRING, true),
3829        ])
3830        .unwrap();
3831        let schema = schema
3832            .with_field_inserted_after(None, StructField::new("age", DataType::STRING, true))
3833            .expect("with field inserted should produce a valid schema");
3834
3835        assert_eq!(schema.num_fields(), 3);
3836        assert_eq!(schema.field_at_index(0).unwrap().name(), "id");
3837        assert_eq!(schema.field_at_index(1).unwrap().name(), "name");
3838        assert_eq!(schema.field_at_index(2).unwrap().name(), "age");
3839    }
3840
3841    #[test]
3842    fn test_with_field_inserted_after_non_existent_field() {
3843        let schema =
3844            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3845        let new_schema = schema.with_field_inserted_after(
3846            Some("nonexistent"),
3847            StructField::new("name", DataType::STRING, true),
3848        );
3849        assert!(new_schema.is_err());
3850    }
3851
3852    #[test]
3853    fn test_with_field_inserted_after_duplicate_field() {
3854        let schema = StructType::try_new([
3855            StructField::new("id", DataType::INTEGER, false),
3856            StructField::new("name", DataType::STRING, true),
3857        ])
3858        .unwrap();
3859        let new_schema = schema.with_field_inserted_after(
3860            Some("name"),
3861            StructField::new("id", DataType::STRING, true),
3862        );
3863        assert!(new_schema.is_err());
3864        assert_result_error_with_message(new_schema, "Field id already exists");
3865    }
3866
3867    #[test]
3868    fn test_with_field_inserted_before() {
3869        let schema = StructType::try_new([
3870            StructField::new("id", DataType::INTEGER, false),
3871            StructField::new("name", DataType::STRING, true),
3872        ])
3873        .unwrap();
3874        let schema = schema
3875            .with_field_inserted_before(
3876                Some("name"),
3877                StructField::new("age", DataType::STRING, true),
3878            )
3879            .expect("with field inserted before should produce a valid schema");
3880        assert_eq!(schema.num_fields(), 3);
3881        assert_eq!(schema.field_at_index(0).unwrap().name(), "id");
3882        assert_eq!(schema.field_at_index(1).unwrap().name(), "age");
3883        assert_eq!(schema.field_at_index(2).unwrap().name(), "name");
3884    }
3885
3886    #[test]
3887    fn test_with_field_inserted_before_duplicate_field() {
3888        let schema = StructType::try_new([
3889            StructField::new("id", DataType::INTEGER, false),
3890            StructField::new("name", DataType::STRING, true),
3891        ])
3892        .unwrap();
3893        let new_schema = schema.with_field_inserted_before(
3894            Some("name"),
3895            StructField::new("id", DataType::STRING, true),
3896        );
3897        assert!(new_schema.is_err());
3898        assert_result_error_with_message(new_schema, "Field id already exists");
3899    }
3900
3901    #[test]
3902    fn test_with_field_inserted_before_at_beginning() {
3903        let schema = StructType::try_new([
3904            StructField::new("id", DataType::INTEGER, false),
3905            StructField::new("name", DataType::STRING, true),
3906        ])
3907        .unwrap();
3908        let schema = schema
3909            .with_field_inserted_before(None, StructField::new("age", DataType::STRING, true))
3910            .expect("with field inserted before should produce a valid schema");
3911        assert_eq!(schema.num_fields(), 3);
3912        assert_eq!(schema.field_at_index(0).unwrap().name(), "age");
3913        assert_eq!(schema.field_at_index(1).unwrap().name(), "id");
3914        assert_eq!(schema.field_at_index(2).unwrap().name(), "name");
3915    }
3916
3917    #[test]
3918    fn test_with_field_inserted_before_non_existent_field() {
3919        let schema =
3920            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3921        let new_schema = schema.with_field_inserted_before(
3922            Some("nonexistent"),
3923            StructField::new("name", DataType::STRING, true),
3924        );
3925        assert!(new_schema.is_err());
3926    }
3927
3928    #[test]
3929    fn test_with_field_inserted_before_empty_struct() {
3930        let schema = StructType::try_new([]).unwrap();
3931        let schema = schema
3932            .with_field_inserted_before(None, StructField::new("age", DataType::STRING, true))
3933            .expect("with field inserted before on empty struct should succeed");
3934        assert_eq!(schema.num_fields(), 1);
3935        assert_eq!(schema.field_at_index(0).unwrap().name(), "age");
3936    }
3937
3938    #[test]
3939    fn test_with_field_removed() {
3940        let schema =
3941            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3942        let new_schema = schema.with_field_removed("id");
3943        assert_eq!(new_schema.num_fields(), 0);
3944    }
3945
3946    #[test]
3947    fn test_with_field_removed_non_existent_field() {
3948        let schema =
3949            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3950        let new_schema = schema.with_field_removed("nonexistent");
3951        assert_eq!(new_schema.num_fields(), 1);
3952        assert_eq!(new_schema.field_at_index(0).unwrap().name(), "id");
3953    }
3954
3955    #[test]
3956    fn test_with_field_replaced() {
3957        let schema =
3958            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3959        let new_schema = schema
3960            .with_field_replaced("id", StructField::new("name", DataType::STRING, true))
3961            .unwrap();
3962
3963        assert_eq!(new_schema.num_fields(), 1);
3964        assert_eq!(new_schema.field_at_index(0).unwrap().name(), "name");
3965    }
3966
3967    #[test]
3968    fn test_with_field_replaced_non_existent_field() {
3969        let schema =
3970            StructType::try_new([StructField::new("id", DataType::INTEGER, false)]).unwrap();
3971        let new_schema = schema.with_field_replaced(
3972            "nonexistent",
3973            StructField::new("name", DataType::STRING, true),
3974        );
3975        assert!(new_schema.is_err(), "Expected error for non-existent field");
3976    }
3977
3978    /// Schema: { a: { b: { c: double } } } — supports walks at depths 1, 2, and 3.
3979    fn walk_test_schema() -> StructType {
3980        let l3 = StructType::new_unchecked([StructField::new("c", DataType::DOUBLE, false)]);
3981        let l2 = StructType::new_unchecked([StructField::new(
3982            "b",
3983            DataType::Struct(Box::new(l3)),
3984            false,
3985        )]);
3986        StructType::new_unchecked([StructField::new("a", DataType::Struct(Box::new(l2)), false)])
3987    }
3988
3989    #[rstest::rstest]
3990    #[case::single_level(vec!["a"], vec!["a"], DataType::Struct(Box::new(
3991        StructType::new_unchecked([StructField::new("b", DataType::Struct(Box::new(
3992            StructType::new_unchecked([StructField::new("c", DataType::DOUBLE, false)])
3993        )), false)])
3994    )))]
3995    #[case::nested_2(vec!["a", "b"], vec!["a", "b"], DataType::Struct(Box::new(
3996        StructType::new_unchecked([StructField::new("c", DataType::DOUBLE, false)])
3997    )))]
3998    #[case::nested_3(vec!["a", "b", "c"], vec!["a", "b", "c"], DataType::DOUBLE)]
3999    #[test]
4000    fn test_walk_column_fields_happy(
4001        #[case] col_path: Vec<&str>,
4002        #[case] expected_names: Vec<&str>,
4003        #[case] expected_leaf_type: DataType,
4004    ) {
4005        let schema = walk_test_schema();
4006        let fields = schema
4007            .walk_column_fields(&ColumnName::new(col_path.iter().copied()))
4008            .unwrap();
4009        assert_eq!(fields.len(), expected_names.len());
4010        for (field, name) in fields.iter().zip(expected_names.iter()) {
4011            assert_eq!(field.name(), *name);
4012        }
4013        assert_eq!(fields.last().unwrap().data_type(), &expected_leaf_type);
4014    }
4015
4016    #[rstest::rstest]
4017    #[case::empty_path(vec![], "Column path cannot be empty")]
4018    #[case::not_found_top(vec!["x"], "not found in schema")]
4019    #[case::not_found_nested(vec!["a", "x"], "not found in schema")]
4020    #[case::intermediate_not_struct(vec!["a", "b", "c", "d"], "not a struct type")]
4021    #[test]
4022    fn test_walk_column_fields_error(#[case] col_path: Vec<&str>, #[case] expected_error: &str) {
4023        let schema = walk_test_schema();
4024        let result = schema.walk_column_fields(&ColumnName::new(col_path.iter().copied()));
4025        assert_result_error_with_message(result, expected_error);
4026    }
4027
4028    #[test]
4029    fn test_normalize_column_names_to_schema_casing() {
4030        let inner =
4031            StructType::new_unchecked(vec![StructField::new("City", DataType::STRING, false)]);
4032        let schema = StructType::new_unchecked(vec![
4033            StructField::new("id", DataType::INTEGER, false),
4034            StructField::new("EventDate", DataType::DATE, false),
4035            StructField::new("Address", DataType::Struct(Box::new(inner)), false),
4036        ]);
4037
4038        // Mismatched casing -> normalized to schema
4039        let cols = vec![ColumnName::new(["eventdate"])];
4040        assert_eq!(
4041            normalize_column_names_to_schema_casing(&schema, &cols)[0].path(),
4042            ["EventDate"]
4043        );
4044
4045        // Nested path -> each field name normalized
4046        let cols = vec![ColumnName::new(["address", "city"])];
4047        assert_eq!(
4048            normalize_column_names_to_schema_casing(&schema, &cols)[0].path(),
4049            ["Address", "City"]
4050        );
4051
4052        // Already matching -> unchanged
4053        let cols = vec![ColumnName::new(["id"])];
4054        assert_eq!(
4055            normalize_column_names_to_schema_casing(&schema, &cols)[0].path(),
4056            ["id"]
4057        );
4058
4059        // Unrecognized -> keeps original
4060        let cols = vec![ColumnName::new(["nonexistent"])];
4061        assert_eq!(
4062            normalize_column_names_to_schema_casing(&schema, &cols)[0].path(),
4063            ["nonexistent"]
4064        );
4065    }
4066}