Kurtiscwright commented on code in PR #2477:
URL: https://github.com/apache/iceberg-rust/pull/2477#discussion_r3376620521


##########
crates/iceberg/src/arrow/timestamp_tz.rs:
##########
@@ -0,0 +1,415 @@
+// 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.
+
+//! UTC timestamp coercion for Arrow RecordBatches.
+//!
+//! Arrow engines may produce timestamps with timezone "UTC" while Iceberg's
+//! canonical Arrow schema uses "+00:00". This module handles the lossless cast
+//! between UTC-equivalent timezone representations so the parquet writer can
+//! accept data from either convention.
+
+use arrow_array::RecordBatch;
+use arrow_cast::cast;
+use arrow_schema::SchemaRef as ArrowSchemaRef;
+
+use crate::{Error, ErrorKind, Result};
+
+/// Coerce timestamp columns in `batch` to match `target_schema` when the only
+/// difference is a UTC-equivalent timezone alias (e.g. "UTC" vs "+00:00").
+pub(crate) fn coerce_timestamp_columns(
+    batch: &RecordBatch,
+    target_schema: &ArrowSchemaRef,
+) -> Result<RecordBatch> {
+    if batch.schema() == *target_schema {
+        return Ok(batch.clone());
+    }
+
+    let mut cols = batch.columns().to_vec();
+    let mut changed = false;
+
+    for (idx, (col, target_field)) in batch
+        .columns()
+        .iter()
+        .zip(target_schema.fields())
+        .enumerate()
+    {
+        if col.data_type() != target_field.data_type()
+            && differs_only_by_utc_timezone(col.data_type(), 
target_field.data_type())
+        {
+            cols[idx] = cast(col, target_field.data_type())?;
+            changed = true;
+        }
+    }
+
+    if !changed {
+        return Ok(batch.clone());
+    }
+
+    RecordBatch::try_new(target_schema.clone(), cols).map_err(|err| {
+        Error::new(
+            ErrorKind::DataInvalid,
+            "Failed to rebuild record batch after casting to target schema.",
+        )
+        .with_source(err)
+    })
+}
+
+/// Returns true if `source` and `target` differ only by UTC-equivalent 
timezone aliases
+/// at any nesting depth. Recurses into List, LargeList, FixedSizeList, 
Struct, and Map.
+fn differs_only_by_utc_timezone(
+    source: &arrow_schema::DataType,
+    target: &arrow_schema::DataType,
+) -> bool {
+    use arrow_schema::DataType;
+    match (source, target) {
+        (s, t) if s == t => false,
+
+        (DataType::Timestamp(s_unit, Some(s_tz)), DataType::Timestamp(t_unit, 
Some(t_tz)))
+            if s_unit == t_unit =>
+        {
+            matches!(
+                (s_tz.as_ref(), t_tz.as_ref()),
+                ("UTC", "+00:00") | ("+00:00", "UTC")
+            )
+        }
+
+        (DataType::List(s_field), DataType::List(t_field))
+        | (DataType::LargeList(s_field), DataType::LargeList(t_field)) => {
+            s_field.name() == t_field.name()
+                && s_field.is_nullable() == t_field.is_nullable()
+                && differs_only_by_utc_timezone(s_field.data_type(), 
t_field.data_type())
+        }
+
+        (DataType::FixedSizeList(s_field, s_size), 
DataType::FixedSizeList(t_field, t_size))
+            if s_size == t_size =>
+        {
+            s_field.name() == t_field.name()
+                && s_field.is_nullable() == t_field.is_nullable()
+                && differs_only_by_utc_timezone(s_field.data_type(), 
t_field.data_type())
+        }
+
+        (DataType::Struct(s_fields), DataType::Struct(t_fields)) => {
+            s_fields.len() == t_fields.len()
+                && s_fields.iter().zip(t_fields.iter()).all(|(sf, tf)| {
+                    sf.name() == tf.name()
+                        && sf.is_nullable() == tf.is_nullable()
+                        && (sf.data_type() == tf.data_type()
+                            || differs_only_by_utc_timezone(sf.data_type(), 
tf.data_type()))
+                })
+        }
+
+        (DataType::Map(s_field, s_sorted), DataType::Map(t_field, t_sorted))
+            if s_sorted == t_sorted =>
+        {
+            differs_only_by_utc_timezone(s_field.data_type(), 
t_field.data_type())
+        }
+
+        _ => false,
+    }
+}
+
+#[cfg(test)]
+mod tests {

Review Comment:
   Maybe I overlooked it, but is there a test that passes in a bad schema at 
the top layer to make sure it gets down to the differs method as expected?



-- 
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