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-4471-f8185fd17edef9b81667c3804e5904a9115c42f7
in repository https://gitbox.apache.org/repos/asf/iceberg-python.git

commit 21440b0f99d557f924d688dba60aea4cfac7ab01
Author: Krishna Prasad Chapagain 
<[email protected]>
AuthorDate: Wed Nov 25 23:36:47 2026 +0000

    Support downcasting time64[ns] to time64[us] on write (#1169) (#4471)
    
    Iceberg time is microsecond precision, so time64[ns] columns previously
    failed schema conversion with 'Unsupported type: time64[ns]'. Mirror the
    existing timestamp[ns] downcast behavior: with the
    'downcast-ns-timestamp-to-us-on-write' property set, time64[ns] converts
    to TimeType (with a warning) and time64[ns] arrays are cast to
    time64[us] on write; without it, conversion raises a TypeError pointing
    at the property. time64[us] behavior is unchanged.
    
    Co-authored-by: Krishna Prasad Chapagain <[email protected]>
---
 pyiceberg/io/pyarrow.py          | 21 +++++++++++++++++++--
 tests/io/test_pyarrow.py         | 29 +++++++++++++++++++++++++++++
 tests/io/test_pyarrow_visitor.py | 16 +++++++++++++++-
 3 files changed, 63 insertions(+), 3 deletions(-)

diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py
index f64cc71e3..5140f717e 100644
--- a/pyiceberg/io/pyarrow.py
+++ b/pyiceberg/io/pyarrow.py
@@ -1604,8 +1604,19 @@ class _ConvertToIceberg(PyArrowSchemaVisitor[IcebergType 
| Schema]):
             return StringType()
         elif pa.types.is_date32(primitive):
             return DateType()
-        elif isinstance(primitive, pa.Time64Type) and primitive.unit == "us":
-            return TimeType()
+        elif isinstance(primitive, pa.Time64Type):
+            if primitive.unit == "us":
+                return TimeType()
+            elif primitive.unit == "ns":
+                if self._downcast_ns_timestamp_to_us:
+                    logger.warning("Iceberg does not yet support 'ns' time 
precision. Downcasting to 'us'.")
+                    return TimeType()
+                else:
+                    raise TypeError(
+                        "Iceberg does not yet support 'ns' time precision. "
+                        "Use 'downcast-ns-timestamp-to-us-on-write' 
configuration property to automatically "
+                        "downcast 'ns' to 'us' on write.",
+                    )
         elif pa.types.is_timestamp(primitive):
             primitive = cast(pa.TimestampType, primitive)
             if primitive.unit in ("s", "ms", "us"):
@@ -2275,6 +2286,12 @@ class 
ArrowProjectionVisitor(SchemaWithPartnerVisitor[pa.Array, pa.Array | None]
                         elif target_type.unit == "us" and values.type.unit in 
{"s", "ms", "us"}:
                             return values.cast(target_type)
                     raise ValueError(f"Unsupported schema projection from 
{values.type} to {target_type}")
+                elif field.field_type == TimeType():
+                    if pa.types.is_time(target_type) and 
pa.types.is_time(values.type):
+                        # Downcasting of nanoseconds to microseconds
+                        if target_type.unit == "us" and values.type.unit == 
"ns" and self._downcast_ns_timestamp_to_us:
+                            return values.cast(target_type, safe=False)
+                    raise ValueError(f"Unsupported schema projection from 
{values.type} to {target_type}")
                 elif isinstance(field.field_type, (IntegerType, LongType)):
                     # Cast smaller integer types to target type for 
cross-platform compatibility
                     # Only allow widening conversions (smaller bit width to 
larger)
diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py
index 1a55e9f74..428342f32 100644
--- a/tests/io/test_pyarrow.py
+++ b/tests/io/test_pyarrow.py
@@ -4172,6 +4172,35 @@ def 
test__to_requested_schema_timestamps_without_downcast_raises_exception(
     assert "Unsupported schema projection from timestamp[ns] to timestamp[us]" 
in str(exc_info.value)
 
 
+def test__to_requested_schema_time_ns_downcast() -> None:
+    """Test that a time64[ns] column is downcast to time64[us] on write when 
the flag is set."""
+    requested_schema = Schema(NestedField(1, "time_field", TimeType(), 
required=False))
+    file_schema = requested_schema
+
+    arrow_schema = pa.schema([pa.field("time_field", pa.time64("ns"))])
+    data = pa.array([time(12, 0, 0, 1), None], type=pa.time64("ns"))
+    batch = pa.RecordBatch.from_arrays([data], schema=arrow_schema)
+
+    result = _to_requested_schema(requested_schema, file_schema, batch, 
downcast_ns_timestamp_to_us=True, include_field_ids=False)
+
+    assert result.schema[0].type == pa.time64("us")
+    assert result.column(0).to_pylist() == [time(12, 0, 0, 1), None]
+
+
+def test__to_requested_schema_time_ns_without_downcast_raises_exception() -> 
None:
+    requested_schema = Schema(NestedField(1, "time_field", TimeType(), 
required=False))
+    file_schema = requested_schema
+
+    arrow_schema = pa.schema([pa.field("time_field", pa.time64("ns"))])
+    data = pa.array([time(12, 0, 0, 1), None], type=pa.time64("ns"))
+    batch = pa.RecordBatch.from_arrays([data], schema=arrow_schema)
+
+    with pytest.raises(ValueError) as exc_info:
+        _to_requested_schema(requested_schema, file_schema, batch, 
downcast_ns_timestamp_to_us=False, include_field_ids=False)
+
+    assert "Unsupported schema projection from time64[ns] to time64[us]" in 
str(exc_info.value)
+
+
 def test__to_requested_schema_null_map_of_structs() -> None:
     requested_schema = Schema(
         NestedField(
diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py
index da8aa07f6..23b2b0d68 100644
--- a/tests/io/test_pyarrow_visitor.py
+++ b/tests/io/test_pyarrow_visitor.py
@@ -188,10 +188,24 @@ def test_pyarrow_time64_us_to_iceberg() -> None:
 
 def test_pyarrow_time64_ns_to_iceberg() -> None:
     pyarrow_type = pa.time64("ns")
-    with pytest.raises(TypeError, match=re.escape("Unsupported type: 
time64[ns]")):
+    with pytest.raises(
+        TypeError,
+        match=re.escape(
+            "Iceberg does not yet support 'ns' time precision. Use 
'downcast-ns-timestamp-to-us-on-write' "
+            "configuration property to automatically downcast 'ns' to 'us' on 
write."
+        ),
+    ):
         visit_pyarrow(pyarrow_type, _ConvertToIceberg())
 
 
+def test_pyarrow_time64_ns_to_iceberg_downcast() -> None:
+    pyarrow_type = pa.time64("ns")
+    converted_iceberg_type = visit_pyarrow(pyarrow_type, 
_ConvertToIceberg(downcast_ns_timestamp_to_us=True))
+    assert converted_iceberg_type == TimeType()
+    # 'ns' time is downcast to 'us' precision
+    assert visit(converted_iceberg_type, _ConvertToArrowSchema()) == 
pa.time64("us")
+
+
 @pytest.mark.parametrize("precision", ["s", "ms", "us", "ns"])
 def test_pyarrow_timestamp_to_iceberg(precision: str) -> None:
     pyarrow_type = pa.timestamp(unit=precision)

Reply via email to