xanderbailey commented on code in PR #3066:
URL: https://github.com/apache/iceberg-rust/pull/3066#discussion_r4153422799


##########
crates/iceberg/src/spec/schema/assign_fresh_ids.rs:
##########
@@ -0,0 +1,474 @@
+// Licensed to the Apache Software Foundation (ASF) under one
+// or more contributor license agreements.  See the NOTICE file
+// distributed with this work for additional information
+// regarding copyright ownership.  The ASF licenses this file
+// to you under the Apache License, Version 2.0 (the
+// "License"); you may not use this file except in compliance
+// with the License.  You may obtain a copy of the License at
+//
+//   http://www.apache.org/licenses/LICENSE-2.0
+//
+// Unless required by applicable law or agreed to in writing,
+// software distributed under the License is distributed on an
+// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
+// KIND, either express or implied.  See the License for the
+// specific language governing permissions and limitations
+// under the License.
+
+use super::utils::try_insert_field;
+use super::*;
+
+/// Reassigns `schema`'s field ids, reusing ids from `base` for fields whose 
full name is unchanged
+/// and drawing fresh ids from `start_from` upwards for everything else.
+///
+/// `start_from` must be past every id the table has ever assigned, not merely 
past `base`'s ids:
+/// pass `table_metadata.last_column_id() + 1`, which also reserves the ids of 
columns already
+/// dropped from `base`. Seeding from a schema's `highest_field_id() + 1` can 
hand a new column the
+/// id of a dropped one. A reused id does not consume a fresh one, so a 
`start_from` that is too low
+/// yields duplicate ids, which surface only as a generic error from `build()`.
+///
+/// The returned `schema_id` is carried over unchanged and is not 
authoritative; it is arbitrated by
+/// 
[`TableMetadataBuilder::add_schema`](crate::spec::TableMetadataBuilder::add_schema).
+pub(crate) fn assign_fresh_ids(schema: Schema, base: &Schema, start_from: i32) 
-> Result<Schema> {
+    let Schema {
+        r#struct,
+        schema_id,
+        identifier_field_ids,
+        alias_to_id,
+        id_to_name,
+        ..
+    } = schema;
+    let mut assigner = AssignFreshIds::new(id_to_name, base, start_from);
+    let fields = assigner.assign_fields(r#struct.fields().to_vec())?;
+    let identifier_field_ids = 
assigner.apply_to_identifier_fields(identifier_field_ids)?;
+    let alias_to_id = assigner.apply_to_aliases(alias_to_id)?;
+
+    Schema::builder()
+        .with_schema_id(schema_id)
+        .with_fields(fields)
+        .with_identifier_field_ids(identifier_field_ids)
+        .with_alias(alias_to_id)
+        .build()
+}
+
+struct AssignFreshIds {
+    next_field_id: i32,
+    target_names: HashMap<i32, String>,
+    base_ids: HashMap<String, i32>,
+    old_to_new_id: HashMap<i32, i32>,
+}
+
+impl AssignFreshIds {
+    fn new(target_names: HashMap<i32, String>, base: &Schema, start_from: i32) 
-> Self {
+        Self {
+            next_field_id: start_from,
+            target_names,
+            base_ids: base
+                .field_id_to_name_map()
+                .iter()
+                .map(|(id, name)| (name.clone(), *id))
+                .collect(),
+            old_to_new_id: HashMap::new(),
+        }
+    }
+
+    /// Returns `base`'s id when the field's full name is unchanged, otherwise 
consumes a fresh id by
+    /// advancing `next_field_id`.
+    fn resolve_or_assign_id(&mut self, old_id: i32) -> Result<i32> {
+        if let Some(id) = self
+            .target_names
+            .get(&old_id)
+            .and_then(|name| self.base_ids.get(name))
+        {
+            return Ok(*id);
+        }
+
+        let id = self.next_field_id;
+        self.next_field_id = self.next_field_id.checked_add(1).ok_or_else(|| {
+            Error::new(
+                ErrorKind::DataInvalid,
+                "Field ID overflowed, cannot add more fields",
+            )
+        })?;
+        Ok(id)
+    }
+
+    fn assign_fields(&mut self, fields: Vec<NestedFieldRef>) -> 
Result<Vec<NestedFieldRef>> {
+        let outer_fields = fields
+            .into_iter()
+            .map(|field| {
+                let new_id = self.resolve_or_assign_id(field.id)?;
+                try_insert_field(&mut self.old_to_new_id, field.id, new_id)?;
+                Ok(Arc::new(Arc::unwrap_or_clone(field).with_id(new_id)))
+            })
+            .collect::<Result<Vec<_>>>()?;
+
+        outer_fields
+            .into_iter()
+            .map(|field| {
+                if field.field_type.is_primitive() {

Review Comment:
   
[e01fc29](https://github.com/apache/iceberg-rust/pull/3066/commits/e01fc29cb4cd3c0b0cf0303e93af8b1926a68adf)
 done, good catch



-- 
This is an automated message from the Apache Git Service.
To respond to the message, please log on to GitHub and use the
URL above to go to the specific comment.

To unsubscribe, e-mail: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to