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