This is an automated email from the ASF dual-hosted git repository.

github-merge-queue[bot] pushed a commit to branch 
gh-readonly-queue/main/pr-3057-d15dca02c53db98de233e43aeebb6e4d0c620c10
in repository https://gitbox.apache.org/repos/asf/iceberg-rust.git

commit f52ec21e03c82eb00adffb0869867265aca0ff28
Author: Xander <[email protected]>
AuthorDate: Mon Nov 16 15:33:44 2026 +0000

    feat(RTAS): add TableMetadataBuilder::build_replacement (#3057)
    
    * feat: add TableMetadataBuilder::build_replacement
    
    Backs `REPLACE TABLE`: swaps the schema, partition spec and sort order
    while keeping the table's uuid, properties and snapshots, and drops the
    main branch so the replaced table has no current snapshot.
    
    Columns the table already has keep their field ids, so data files written
    before the replacement stay readable through the shared columns. New
    columns draw ids above `last_column_id`, never reusing a dropped column's
    id. Partition field ids are likewise reused across historical specs.
    
    Extracts `rebind_to_schema` out of `reassign_ids` so the partition spec
    and sort order can be rebound to a schema whose ids were assigned either
    from scratch or by `assign_fresh_ids`.
    
    Format version 1 is not supported.
    
    * fix docs
    
    * tighten up tests
    
    * nits
    
    * test: cover build_replacement error paths and refs, document id matching
    
    * refactor: take a typed format_version in build_replacement
    
    * refactor: make build_replacement pub(crate) until RTAS uses it
    
    Moves the doc example into a unit test, since a doctest cannot call a
    pub(crate) function.
    
    * fix: return an error when build_replacement runs out of partition ids
    
    Reuses equivalent ids through reuse_partition_field_ids and assigns the
    rest with PartitionSpecBuilder, which errors on overflow instead of
    wrapping. The AddSpec change still carries every field id.
---
 crates/iceberg/src/spec/schema/mod.rs             |   5 +-
 crates/iceberg/src/spec/table_metadata_builder.rs | 930 +++++++++++++++++++++-
 2 files changed, 929 insertions(+), 6 deletions(-)

diff --git a/crates/iceberg/src/spec/schema/mod.rs 
b/crates/iceberg/src/spec/schema/mod.rs
index 4d539b36c..87e5535a6 100644
--- a/crates/iceberg/src/spec/schema/mod.rs
+++ b/crates/iceberg/src/spec/schema/mod.rs
@@ -25,9 +25,7 @@ mod utils;
 mod visitor;
 pub use self::visitor::*;
 pub(super) mod _serde;
-// TODO: Use for table replacement in 
https://github.com/apache/iceberg-rust/issues/3056.
-#[allow(dead_code)]
-pub(crate) mod assign_fresh_ids;
+mod assign_fresh_ids;
 mod id_reassigner;
 mod index;
 mod prune_columns;
@@ -36,6 +34,7 @@ use itertools::{Itertools, zip_eq};
 use serde::{Deserialize, Serialize};
 
 use self::_serde::SchemaEnum;
+pub(crate) use self::assign_fresh_ids::assign_fresh_ids;
 use self::id_reassigner::ReassignFieldIds;
 use self::index::{IndexByName, index_by_id, index_parents};
 pub use self::prune_columns::prune_columns;
diff --git a/crates/iceberg/src/spec/table_metadata_builder.rs 
b/crates/iceberg/src/spec/table_metadata_builder.rs
index 872922039..82c0a521c 100644
--- a/crates/iceberg/src/spec/table_metadata_builder.rs
+++ b/crates/iceberg/src/spec/table_metadata_builder.rs
@@ -20,12 +20,13 @@ use std::sync::Arc;
 
 use uuid::Uuid;
 
+use super::schema::assign_fresh_ids;
 use super::{
     DEFAULT_PARTITION_SPEC_ID, DEFAULT_SCHEMA_ID, FormatVersion, MAIN_BRANCH, 
MetadataLog,
     ONE_MINUTE_MS, PartitionField, PartitionSpec, PartitionSpecBuilder, 
PartitionStatisticsFile,
     Schema, SchemaRef, Snapshot, SnapshotLog, SnapshotReference, 
SnapshotRetention, SortOrder,
     SortOrderRef, StatisticsFile, StructType, TableMetadata, TableProperties, 
Transform,
-    UNPARTITIONED_LAST_ASSIGNED_ID, UnboundPartitionSpec,
+    UNPARTITIONED_LAST_ASSIGNED_ID, UnboundPartitionField, 
UnboundPartitionSpec,
 };
 use crate::error::{Error, ErrorKind, Result, invalid_data};
 use crate::spec::{EncryptedKey, INITIAL_ROW_ID, 
MIN_FORMAT_VERSION_ROW_LINEAGE};
@@ -192,6 +193,82 @@ impl TableMetadataBuilder {
         )
     }
 
+    /// Replaces the table's schema, partition spec and sort order, leaving it 
with no
+    /// current snapshot. Backs `REPLACE TABLE`.
+    ///
+    /// The table keeps its uuid, properties and snapshots, so earlier 
snapshots stay readable.
+    /// Only the `main` branch is removed; other branches and tags are kept.
+    ///
+    /// Columns are matched to the current schema by full name and keep their 
field ids, even
+    /// when their type changes; new columns get ids above `last_column_id`, 
never a dropped
+    /// column's id.
+    ///
+    /// Partition fields reuse the highest id an equivalent field has in any 
of the table's specs,
+    /// and other fields get ids above `last_partition_id`.
+    ///
+    /// `location` moves the table, `None` leaves it in place. 
`format_version` upgrades the table,
+    /// `None` keeps its version. `properties` are applied on top of the 
existing ones, so an
+    /// existing `write.parquet.compression-codec` is kept.
+    ///
+    /// The caller adds the snapshot holding the new contents, if any, before 
building.
+    ///
+    /// # Errors
+    /// - The table is format version 1, which is not supported.
+    /// - `format_version` would downgrade the table.
+    /// - The partition spec or sort order names a column missing from 
`schema`.
+    /// - `schema` takes the name of a partition field in one of the table's 
specs without being
+    ///   that field's source column.
+    /// - `properties` contains a reserved property.
+    // TODO: Use for table replacement in 
https://github.com/apache/iceberg-rust/issues/3056.
+    #[allow(dead_code)]
+    pub(crate) fn build_replacement(
+        self,
+        schema: Schema,
+        spec: impl Into<UnboundPartitionSpec>,
+        sort_order: SortOrder,
+        location: Option<String>,
+        format_version: Option<FormatVersion>,
+        properties: HashMap<String, String>,
+    ) -> Result<Self> {
+        if self.metadata.format_version == FormatVersion::V1 {
+            return Err(Error::new(
+                ErrorKind::FeatureUnsupported,
+                "Table replacement is not supported for format version 1",
+            ));
+        }
+
+        let format_version = 
format_version.unwrap_or(self.metadata.format_version);
+        let spec = spec.into();
+
+        let previous_id_to_name = schema.field_id_to_name_map().clone();
+        let fresh_schema = assign_fresh_ids(
+            schema,
+            self.get_current_schema()?,
+            self.metadata.last_column_id,
+        )?;
+
+        let (fresh_spec, fresh_sort_order) =
+            Self::rebind_to_schema(&previous_id_to_name, &fresh_schema, spec, 
sort_order)?;
+        let fresh_spec = self.reassign_partition_field_ids(fresh_spec, 
&fresh_schema)?;
+
+        let mut builder = self.upgrade_format_version(format_version)?;
+        if builder.metadata.refs.contains_key(MAIN_BRANCH) {
+            builder = builder.remove_ref(MAIN_BRANCH);
+        }
+
+        let builder = builder
+            .add_current_schema(fresh_schema)?
+            .add_default_partition_spec(fresh_spec)?
+            .add_default_sort_order(fresh_sort_order)?;
+
+        let builder = match location {
+            Some(location) => builder.set_location(location),
+            None => builder,
+        };
+
+        builder.set_properties(properties)
+    }
+
     /// Changes uuid of table metadata.
     pub fn assign_uuid(mut self, uuid: Uuid) -> Self {
         if self.metadata.table_uuid != uuid {
@@ -1246,6 +1323,38 @@ impl TableMetadataBuilder {
             .collect()
     }
 
+    /// Gives each field of `spec` the highest id an equivalent field has in 
the table's specs, or
+    /// the next id above `last_partition_id`.
+    fn reassign_partition_field_ids(
+        &self,
+        spec: PartitionSpec,
+        schema: &Schema,
+    ) -> Result<UnboundPartitionSpec> {
+        let fields = spec
+            .fields()
+            .iter()
+            .map(|field| {
+                UnboundPartitionField::builder()
+                    .source_ids(vec![field.source_id])
+                    .name(field.name.clone())
+                    .transform(field.transform)
+                    .build()
+            })
+            .collect::<Result<Vec<_>>>()?;
+        let spec = self.reuse_partition_field_ids(
+            UnboundPartitionSpec::builder()
+                .add_partition_fields(fields)?
+                .build(),
+        )?;
+
+        Ok(
+            PartitionSpecBuilder::new_from_unbound(spec, schema.clone())?
+                .with_last_assigned_field_id(self.metadata.last_partition_id)
+                .build()?
+                .into_unbound(),
+        )
+    }
+
     fn reassign_ids(
         schema: Schema,
         spec: UnboundPartitionSpec,
@@ -1259,6 +1368,20 @@ impl TableMetadataBuilder {
             .with_reassigned_field_ids(FIRST_FIELD_ID)
             .build()?;
 
+        let (fresh_spec, fresh_sort_order) =
+            Self::rebind_to_schema(&previous_id_to_name, &fresh_schema, spec, 
sort_order)?;
+
+        Ok((fresh_schema, fresh_spec, fresh_sort_order))
+    }
+
+    /// Rebuilds `spec` and `sort_order` against `fresh_schema`, looking up 
each source column by
+    /// the name `previous_id_to_name` gives for the field id they were built 
against.
+    fn rebind_to_schema(
+        previous_id_to_name: &HashMap<i32, String>,
+        fresh_schema: &Schema,
+        spec: UnboundPartitionSpec,
+        sort_order: SortOrder,
+    ) -> Result<(PartitionSpec, SortOrder)> {
         // Re-build partition spec with new ids
         let mut fresh_spec = PartitionSpecBuilder::new(fresh_schema.clone());
         for field in spec.fields() {
@@ -1300,9 +1423,9 @@ impl TableMetadataBuilder {
             field.source_id = new_field_id;
             fresh_order.with_sort_field(field);
         }
-        let fresh_sort_order = fresh_order.build(&fresh_schema)?;
+        let fresh_sort_order = fresh_order.build(fresh_schema)?;
 
-        Ok((fresh_schema, fresh_spec, fresh_sort_order))
+        Ok((fresh_spec, fresh_sort_order))
     }
 
     fn check_format_compatibility(&self) -> Result<()> {
@@ -4405,6 +4528,807 @@ mod tests {
         assert_eq!(field_ids, vec![1000, 1001, 1002]); // Reused 1000, 1001; 
new 1002
     }
 
+    fn unbound_field(source_id: i32, name: &str, transform: Transform) -> 
UnboundPartitionField {
+        UnboundPartitionField::builder()
+            .source_ids(vec![source_id])
+            .name(name)
+            .transform(transform)
+            .build()
+            .unwrap()
+    }
+
+    fn replacement_schema() -> Schema {
+        // `z` and `x` already exist in the table, `w` is new, `y` is dropped.
+        Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "z", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(3, "w", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap()
+    }
+
+    fn partition_replacement_builder(format_version: FormatVersion) -> 
TableMetadataBuilder {
+        let schema = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "y", 
Type::Primitive(PrimitiveType::Long)).into(),
+            ])
+            .build()
+            .unwrap();
+        let spec = UnboundPartitionSpec::builder()
+            .add_partition_field(unbound_field(1, "x", Transform::Identity))
+            .unwrap()
+            .add_partition_field(unbound_field(2, "y", Transform::Identity))
+            .unwrap()
+            .build();
+
+        TableMetadataBuilder::new(
+            schema,
+            spec,
+            SortOrder::unsorted_order(),
+            TEST_LOCATION.to_string(),
+            format_version,
+            HashMap::new(),
+        )
+        .unwrap()
+        .build()
+        .unwrap()
+        .metadata
+        .into_builder(Some(
+            "s3://bucket/test/location/metadata/metadata1.json".to_string(),
+        ))
+    }
+
+    fn populated_builder() -> TableMetadataBuilder {
+        let builder = builder_without_changes(FormatVersion::V2);
+        let snapshot = Snapshot::builder()
+            .with_snapshot_id(1)
+            .with_timestamp_ms(builder.metadata.last_updated_ms + 1)
+            .with_sequence_number(0)
+            .with_schema_id(0)
+            .with_manifest_list("/snap-1.avro")
+            .with_summary(Summary {
+                operation: Operation::Append,
+                additional_properties: HashMap::new(),
+            })
+            .build();
+
+        builder
+            .add_snapshot(snapshot)
+            .unwrap()
+            .set_ref(MAIN_BRANCH, SnapshotReference {
+                snapshot_id: 1,
+                retention: SnapshotRetention::branch(None, None, None),
+            })
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata
+            .into_builder(Some(
+                
"s3://bucket/test/location/metadata/metadata2.json".to_string(),
+            ))
+    }
+
+    fn replaced_schema() -> Schema {
+        Schema::builder()
+            .with_schema_id(1)
+            .with_fields(vec![
+                NestedField::required(3, "z", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(4, "w", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap()
+    }
+
+    #[test]
+    fn 
test_build_replacement_keeps_existing_field_ids_and_assigns_new_ones_above_last_column_id()
 {
+        let metadata = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(metadata.current_schema().as_ref(), &replaced_schema());
+        assert_eq!(metadata.last_column_id, 4);
+    }
+
+    #[test]
+    fn test_build_replacement_does_not_reuse_the_id_of_a_dropped_column() {
+        let without_y = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+            ])
+            .build()
+            .unwrap();
+        let replacement = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "w", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap();
+
+        let metadata = partition_replacement_builder(FormatVersion::V2)
+            .add_current_schema(without_y)
+            .unwrap()
+            .build_replacement(
+                replacement,
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        let expected = Schema::builder()
+            .with_schema_id(2)
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(3, "w", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap();
+        assert_eq!(metadata.current_schema().as_ref(), &expected);
+        assert_eq!(metadata.last_column_id, 3);
+    }
+
+    #[test]
+    fn 
test_build_replacement_resolves_spec_and_sort_order_source_ids_against_the_replacement_schema()
+     {
+        let spec = UnboundPartitionSpec::builder()
+            .add_partition_field(unbound_field(3, "w", Transform::Identity))
+            .unwrap()
+            .build();
+        let sort_field = SortField {
+            source_id: 3,
+            transform: Transform::Identity,
+            direction: SortDirection::Ascending,
+            null_order: NullOrder::First,
+        };
+        let sort_order = SortOrder::builder()
+            .with_sort_field(sort_field.clone())
+            .build(&replacement_schema())
+            .unwrap();
+
+        let metadata = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                spec,
+                sort_order,
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        let expected_spec = PartitionSpec::builder(replaced_schema())
+            .with_spec_id(1)
+            .add_unbound_field(unbound_field(4, "w", 
Transform::Identity).with_field_id(1001))
+            .unwrap()
+            .build()
+            .unwrap();
+        let expected_sort_order = SortOrder::builder()
+            .with_order_id(2)
+            .with_sort_field(SortField {
+                source_id: 4,
+                ..sort_field
+            })
+            .build(&replaced_schema())
+            .unwrap();
+        assert_eq!(metadata.default_partition_spec().as_ref(), &expected_spec);
+        assert_eq!(metadata.default_sort_order().as_ref(), 
&expected_sort_order);
+    }
+
+    #[test]
+    fn test_build_replacement_reassigns_partition_ids_for_v2() {
+        let updated_schema = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "z", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap();
+        let updated_spec = UnboundPartitionSpec::builder()
+            .add_partition_field(unbound_field(2, "z_bucket", 
Transform::Bucket(8)))
+            .unwrap()
+            .add_partition_field(unbound_field(1, "x", Transform::Identity))
+            .unwrap()
+            .build();
+
+        let result = partition_replacement_builder(FormatVersion::V2)
+            .build_replacement(
+                updated_schema,
+                updated_spec,
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap();
+        let metadata = &result.metadata;
+
+        let expected_spec = 
PartitionSpec::builder(metadata.current_schema().clone())
+            .with_spec_id(1)
+            .add_unbound_fields([
+                unbound_field(3, "z_bucket", 
Transform::Bucket(8)).with_field_id(1002),
+                unbound_field(1, "x", Transform::Identity).with_field_id(1000),
+            ])
+            .unwrap()
+            .build()
+            .unwrap();
+        assert_eq!(metadata.default_partition_spec().as_ref(), &expected_spec);
+        assert_eq!(metadata.last_partition_id, 1002);
+        assert!(result.changes.contains(&TableUpdate::AddSpec {
+            spec: expected_spec.into_unbound()
+        }));
+    }
+
+    #[test]
+    fn 
test_build_replacement_rejects_a_new_partition_field_when_no_partition_id_is_left()
 {
+        let mut builder = partition_replacement_builder(FormatVersion::V2);
+        builder.metadata.last_partition_id = i32::MAX;
+        let updated_schema = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "z", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap();
+        let updated_spec = UnboundPartitionSpec::builder()
+            .add_partition_field(unbound_field(2, "z_bucket", 
Transform::Bucket(8)))
+            .unwrap()
+            .build();
+
+        let err = builder
+            .build_replacement(
+                updated_schema,
+                updated_spec,
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Cannot assign more partition ids. Overflow."
+            )
+        );
+    }
+
+    #[test]
+    fn 
test_build_replacement_keeps_the_table_and_its_snapshots_but_not_its_current_one()
 {
+        let base = populated_builder();
+        let previous = base.metadata.clone();
+
+        let metadata = base
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(metadata.table_uuid, previous.table_uuid);
+        assert_eq!(metadata.location, previous.location);
+        assert_eq!(metadata.current_snapshot_id, None);
+        assert_eq!(metadata.snapshots, previous.snapshots);
+        assert_eq!(metadata.snapshot_log, previous.snapshot_log);
+        assert_eq!(metadata.schema_by_id(0), previous.schema_by_id(0));
+    }
+
+    #[test]
+    fn 
test_build_replacement_then_adding_a_snapshot_makes_it_current_on_main() {
+        let builder = populated_builder()
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap();
+        let snapshot = Snapshot::builder()
+            .with_snapshot_id(2)
+            .with_timestamp_ms(builder.metadata.last_updated_ms + 1)
+            .with_sequence_number(builder.metadata.next_sequence_number())
+            .with_schema_id(builder.metadata.current_schema_id)
+            .with_manifest_list("/snap-2.avro")
+            .with_summary(Summary {
+                operation: Operation::Overwrite,
+                additional_properties: HashMap::new(),
+            })
+            .build();
+        let main = SnapshotReference {
+            snapshot_id: 2,
+            retention: SnapshotRetention::branch(None, None, None),
+        };
+
+        let metadata = builder
+            .add_snapshot(snapshot.clone())
+            .unwrap()
+            .set_ref(MAIN_BRANCH, main.clone())
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(metadata.current_snapshot(), Some(&Arc::new(snapshot)));
+        assert_eq!(
+            metadata.refs,
+            HashMap::from([(MAIN_BRANCH.to_string(), main)])
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_changes_describe_the_replacement() {
+        let changes = populated_builder()
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .changes;
+
+        assert_eq!(changes, vec![
+            TableUpdate::RemoveSnapshotRef {
+                ref_name: MAIN_BRANCH.to_string()
+            },
+            TableUpdate::AddSchema {
+                schema: replaced_schema()
+            },
+            TableUpdate::SetCurrentSchema {
+                schema_id: TableMetadataBuilder::LAST_ADDED
+            },
+            TableUpdate::AddSpec {
+                spec: UnboundPartitionSpec::builder().with_spec_id(1).build()
+            },
+            TableUpdate::SetDefaultSpec {
+                spec_id: TableMetadataBuilder::LAST_ADDED
+            },
+            TableUpdate::AddSortOrder {
+                sort_order: SortOrder::unsorted_order()
+            },
+            TableUpdate::SetDefaultSortOrder {
+                sort_order_id: TableMetadataBuilder::LAST_ADDED as i64
+            },
+        ]);
+    }
+
+    #[test]
+    fn test_build_replacement_moves_the_table_when_given_a_location() {
+        let metadata = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                Some("s3://bucket/somewhere/else".to_string()),
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(metadata.location, "s3://bucket/somewhere/else");
+    }
+
+    #[test]
+    fn test_build_replacement_applies_format_version_and_properties() {
+        let result = builder_without_changes(FormatVersion::V2)
+            .set_properties(HashMap::from_iter([(
+                "existing".to_string(),
+                "value".to_string(),
+            )]))
+            .unwrap()
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                Some(FormatVersion::V3),
+                HashMap::from_iter([("new".to_string(), "value".to_string())]),
+            )
+            .unwrap()
+            .build()
+            .unwrap();
+
+        assert_eq!(result.metadata.format_version, FormatVersion::V3);
+        assert_eq!(
+            result.metadata.properties,
+            HashMap::from_iter([
+                ("existing".to_string(), "value".to_string()),
+                ("new".to_string(), "value".to_string()),
+            ])
+        );
+        assert!(result.changes.contains(&TableUpdate::UpgradeFormatVersion {
+            format_version: FormatVersion::V3
+        }));
+        assert!(result.changes.contains(&TableUpdate::SetProperties {
+            updates: HashMap::from_iter([("new".to_string(), 
"value".to_string())])
+        }));
+    }
+
+    #[test]
+    fn 
test_build_replacement_with_everything_unchanged_reuses_the_existing_ids() {
+        let base = builder_without_changes(FormatVersion::V2)
+            .build()
+            .unwrap()
+            .metadata;
+        let schema = base.current_schema().as_ref().clone();
+        let spec = base
+            .default_partition_spec()
+            .as_ref()
+            .clone()
+            .into_unbound();
+        let sort_order = base.default_sort_order().as_ref().clone();
+
+        let result = base
+            .clone()
+            .into_builder(Some(
+                
"s3://bucket/test/location/metadata/metadata2.json".to_string(),
+            ))
+            .build_replacement(
+                schema.clone(),
+                spec.clone(),
+                sort_order.clone(),
+                None,
+                Some(FormatVersion::V3),
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap();
+
+        let metadata = &result.metadata;
+        assert_eq!(metadata.schemas, base.schemas);
+        assert_eq!(metadata.current_schema_id, base.current_schema_id);
+        assert_eq!(metadata.last_column_id, base.last_column_id);
+        assert_eq!(metadata.partition_specs, base.partition_specs);
+        assert_eq!(metadata.default_spec, base.default_spec);
+        assert_eq!(metadata.last_partition_id, base.last_partition_id);
+        assert_eq!(metadata.sort_orders, base.sort_orders);
+        assert_eq!(metadata.default_sort_order_id, base.default_sort_order_id);
+        assert_eq!(result.changes, vec![
+            TableUpdate::UpgradeFormatVersion {
+                format_version: FormatVersion::V3
+            },
+            TableUpdate::AddSchema { schema },
+            TableUpdate::AddSpec { spec },
+            TableUpdate::AddSortOrder { sort_order },
+        ]);
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_v1() {
+        let err = builder_without_changes(FormatVersion::V1)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::FeatureUnsupported,
+                "Table replacement is not supported for format version 1"
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_v1_with_format_upgrade() {
+        let err = builder_without_changes(FormatVersion::V1)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                Some(FormatVersion::V2),
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::FeatureUnsupported,
+                "Table replacement is not supported for format version 1"
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_reserved_properties() {
+        let err = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::from_iter([(
+                    TableProperties::PROPERTY_UUID.to_string(),
+                    "ignored".to_string(),
+                )]),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Table properties should not contain reserved properties, but 
got: [uuid]"
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_a_spec_on_a_missing_column() {
+        let err = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder()
+                    .add_partition_field(unbound_field(99, "nope", 
Transform::Identity))
+                    .unwrap()
+                    .build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Cannot find source column with id 99 for partition column 
nope in schema."
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_a_format_version_downgrade() {
+        let err = builder_without_changes(FormatVersion::V3)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                Some(FormatVersion::V2),
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Cannot downgrade FormatVersion from v3 to v2"
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_a_sort_order_on_a_missing_column() {
+        let sort_order = SortOrder::builder()
+            .with_sort_field(SortField {
+                source_id: 99,
+                transform: Transform::Identity,
+                direction: SortDirection::Ascending,
+                null_order: NullOrder::First,
+            })
+            .build_unbound()
+            .unwrap();
+
+        let err = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                sort_order,
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Cannot find source column with id 99 for sort column in 
schema."
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_rejects_a_column_named_after_a_partition_field() 
{
+        let builder = TableMetadataBuilder::new(
+            schema(),
+            UnboundPartitionSpec::builder()
+                .add_partition_field(unbound_field(1, "x_bucket", 
Transform::Bucket(8)))
+                .unwrap()
+                .build(),
+            SortOrder::unsorted_order(),
+            TEST_LOCATION.to_string(),
+            FormatVersion::V2,
+            HashMap::new(),
+        )
+        .unwrap()
+        .build()
+        .unwrap()
+        .metadata
+        .into_builder(Some(
+            "s3://bucket/test/location/metadata/metadata1.json".to_string(),
+        ));
+        let replacement = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::Long)).into(),
+                NestedField::required(2, "x_bucket", 
Type::Primitive(PrimitiveType::Long)).into(),
+            ])
+            .build()
+            .unwrap();
+
+        let err = builder
+            .build_replacement(
+                replacement,
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap_err();
+
+        assert_eq!(
+            (err.kind(), err.message()),
+            (
+                ErrorKind::DataInvalid,
+                "Cannot set current schema 1: field 'x_bucket' with id 4 
conflicts with a \
+                 partition field of that name in spec 0 sourced from field id 
1"
+            )
+        );
+    }
+
+    #[test]
+    fn test_build_replacement_keeps_refs_other_than_main() {
+        let audit = SnapshotReference {
+            snapshot_id: 1,
+            retention: SnapshotRetention::branch(None, None, None),
+        };
+        let release = SnapshotReference {
+            snapshot_id: 1,
+            retention: SnapshotRetention::Tag {
+                max_ref_age_ms: None,
+            },
+        };
+        let builder = populated_builder()
+            .set_ref("audit", audit.clone())
+            .unwrap()
+            .set_ref("release", release.clone())
+            .unwrap();
+
+        let metadata = builder
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(
+            metadata.refs,
+            HashMap::from_iter([
+                ("audit".to_string(), audit),
+                ("release".to_string(), release),
+            ])
+        );
+        assert_eq!(metadata.current_snapshot_id, None);
+    }
+
+    #[test]
+    fn test_build_replacement_keeps_the_id_of_a_column_whose_type_changes() {
+        let replacement = Schema::builder()
+            .with_fields(vec![
+                NestedField::required(1, "x", 
Type::Primitive(PrimitiveType::String)).into(),
+            ])
+            .build()
+            .unwrap();
+
+        let metadata = builder_without_changes(FormatVersion::V2)
+            .build_replacement(
+                replacement,
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        let x = metadata.current_schema().field_by_name("x").unwrap();
+        assert_eq!(x.id, 1);
+        assert_eq!(*x.field_type, Type::Primitive(PrimitiveType::String));
+    }
+
+    #[test]
+    fn test_build_replacement_keeps_the_existing_compression_codec() {
+        let codec = HashMap::from_iter([(
+            TableProperties::PROPERTY_PARQUET_COMPRESSION_CODEC.to_string(),
+            "gzip".to_string(),
+        )]);
+
+        let metadata = builder_without_changes(FormatVersion::V2)
+            .set_properties(codec.clone())
+            .unwrap()
+            .build_replacement(
+                replacement_schema(),
+                UnboundPartitionSpec::builder().build(),
+                SortOrder::unsorted_order(),
+                None,
+                None,
+                HashMap::new(),
+            )
+            .unwrap()
+            .build()
+            .unwrap()
+            .metadata;
+
+        assert_eq!(metadata.properties, codec);
+    }
+
     #[test]
     fn test_highest_equivalent_field_ids_is_independent_of_field_order() {
         let field = |source_id, field_id, transform| PartitionField {

Reply via email to