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