diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 397160ab81..cfcf5722e5 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -141,6 +141,7 @@ ) from pyiceberg.partitioning import PartitionFieldValue, PartitionKey, PartitionSpec from pyiceberg.schema import ( + Accessor, PartnerAccessor, PreOrderSchemaVisitor, Schema, @@ -3493,7 +3494,13 @@ def _dataframe_to_data_files( ), ) else: - partitions = _determine_partitions(spec=table_metadata.spec(), schema=table_metadata.schema(), arrow_table=df) + partitions = _determine_partitions( + spec=table_metadata.spec(), + schema=table_metadata.schema(), + arrow_table=df, + input_schema=task_schema, + downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, + ) yield from write_file( io=io, table_metadata=table_metadata, @@ -3517,9 +3524,18 @@ class _TablePartition: arrow_table_partition: pa.Table -def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.Table) -> Iterable[_TablePartition]: +def _determine_partitions( + spec: PartitionSpec, + schema: Schema, + arrow_table: pa.Table, + input_schema: Schema | None = None, + downcast_ns_timestamp_to_us: bool = False, +) -> Iterable[_TablePartition]: """Based on the iceberg table partition spec, filter the arrow table into partitions with their keys. + The source columns are projected the way write_file does, by field ID in input_schema (the Iceberg schema of the + arrow table, schema if not given), so the partition values are computed from the values that are written. + Example: Input: An arrow table with partition key of ['n_legs', 'year'] and with data of @@ -3540,12 +3556,19 @@ def _determine_partitions(spec: PartitionSpec, schema: Schema, arrow_table: pa.T name = f"_{name}" partition_fields.append(name) + source_schema = prune_columns(schema, {field.source_id for field in spec.fields}, select_full_types=False) + input_schema = input_schema if input_schema is not None else schema + source_batches = [ + _to_requested_schema(source_schema, input_schema, batch, downcast_ns_timestamp_to_us) + for batch in arrow_table.to_batches() + ] + if not source_batches: + return + sources = pa.Table.from_batches(source_batches) + for partition, name in zip(spec.fields, partition_fields, strict=True): source_field = schema.find_field(partition.source_id) - full_field_name = schema.find_column_name(partition.source_id) - if full_field_name is None: - raise ValueError(f"Could not find column name for field ID: {partition.source_id}") - field_array = _get_field_from_arrow_table(arrow_table, full_field_name) + field_array = _get_field_from_arrow_table(sources, source_schema, partition.source_id) partition_array = partition.transform.pyarrow_transform(source_field.field_type)(field_array) # PyArrow has no group by or equality kernels for extension types such as arrow.uuid, so use their storage type if isinstance(partition_array.type, pa.BaseExtensionType): @@ -3591,30 +3614,15 @@ def _partition_value_filter(partition_field_name: str, value: Any) -> pc.Express return pc.field(partition_field_name) == value -def _get_field_from_arrow_table(arrow_table: pa.Table, field_path: str) -> pa.Array: - """Get a field from an Arrow table, supporting both literal field names and nested field paths. +def _get_field_from_arrow_table(arrow_table: pa.Table, schema: Schema, field_id: int) -> pa.Array: + """Get a field, which can be nested in structs, from an Arrow table that has the layout of schema. - This function handles two cases: - 1. Literal field names that may contain dots (e.g., "some.id") - 2. Nested field paths using dot notation (e.g., "bar.baz" for nested access) - - Args: - arrow_table: The Arrow table containing the field - field_path: Field name or dot-separated path - - Returns: - The field as a PyArrow Array - - Raises: - KeyError: If the field path cannot be resolved + The field is found by position, like Java's Accessors, so the names on its path can contain dots. """ - # Try exact column name match (handles field names containing literal dots) - if field_path in arrow_table.column_names: - return arrow_table[field_path] - - # If not found as exact name, treat as nested field path - path_parts = field_path.split(".") - # Get the struct column from the table (e.g., "bar" from "bar.baz") - field_array = arrow_table[path_parts[0]] - # Navigate into the struct using the remaining path parts - return pc.struct_field(field_array, path_parts[1:]) + positions: list[int] = [] + accessor: Accessor | None = schema.accessor_for_field(field_id) + while accessor is not None: + positions.append(accessor.position) + accessor = accessor.inner + column, *nested = positions + return pc.struct_field(arrow_table.column(column), nested) if nested else arrow_table.column(column) diff --git a/tests/catalog/test_catalog_behaviors.py b/tests/catalog/test_catalog_behaviors.py index 4e51a4dbda..bd1c4830e8 100644 --- a/tests/catalog/test_catalog_behaviors.py +++ b/tests/catalog/test_catalog_behaviors.py @@ -781,6 +781,89 @@ def test_remove_properties_already_removed_by_concurrent_commit( # Append table +def test_append_to_identity_partitioned_table_with_dotted_names(catalog: Catalog) -> None: + catalog.create_namespace("default") + # The names from the top-level column down to the partition source, where a name can contain dots + paths = [("a.b", "c"), ("a", "b.c"), ("root", "a.b", "c")] + for i, path in enumerate(paths): + column_type: pa.DataType = pa.string() + values: list[Any] = ["x", "y", None] + for name in reversed(path[1:]): + column_type = pa.struct([(name, column_type)]) + values = [{name: value} for value in values] + # The fields of a null struct are stored as nulls, so the last row is in the null partition too + values.append(None) + arrow_schema = pa.schema([("id", pa.int64()), (path[0], column_type)]) + df = pa.Table.from_pydict({"id": [1, 2, 3, 4], path[0]: values}, schema=arrow_schema) + tbl = catalog.create_table(f"default.dotted_partition_source_{i}", schema=df.schema) + with tbl.update_spec() as update: + update.add_field(".".join(path), IdentityTransform(), "p") + + tbl.append(df) + + assert sorted(tbl.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == df.to_pylist(), path + assert {task.file.partition[0] for task in tbl.scan().plan_files()} == {"x", "y", None}, path + + +def test_append_with_field_ids_after_swapping_column_names(catalog: Catalog) -> None: + catalog.create_namespace("default") + struct_type = pa.struct([("c", pa.string())]) + # Each case swaps the names of the two columns after the Arrow table took its field IDs from the table schema + cases: list[tuple[pa.Schema, dict[str, Any], str, str]] = [ + (pa.schema([("a", pa.string()), ("b", pa.string())]), {"a": "x", "b": "y"}, "a", "b"), + (pa.schema([("left", struct_type), ("a.b", struct_type)]), {"left": {"c": "x"}, "a.b": {"c": "y"}}, "left.c", "a.b.c"), + ] + for i, (arrow_schema, row, source_name, renamed_source_name) in enumerate(cases): + tbl = catalog.create_table(f"default.swapped_names_{i}", schema=arrow_schema) + with tbl.update_spec() as spec_update: + spec_update.add_field(source_name, IdentityTransform(), "p") + df = pa.Table.from_pylist([row], schema=tbl.schema().as_arrow()) + first, second = arrow_schema.names + for old_name, new_name in [(first, "tmp"), (second, first), ("tmp", second)]: + with tbl.update_schema() as schema_update: + schema_update.rename_column(old_name, new_name) + + tbl.append(df) + + # The partition value comes from the column that the source field is written from + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == ["x"], source_name + swapped_row = {first: row[second], second: row[first]} + assert tbl.scan(row_filter=f"{renamed_source_name} = 'x'").to_arrow().to_pylist() == [swapped_row], source_name + + +def test_append_without_optional_partition_source_columns(catalog: Catalog) -> None: + catalog.create_namespace("default") + table_schema = pa.schema( + [ + ("id", pa.int64()), + ("region", pa.string()), + ("shipping", pa.struct([("country", pa.string()), ("zip", pa.string())])), + ("billing", pa.struct([("country", pa.string())])), + ] + ) + # The input has no region and billing columns, and its shipping struct has no country field + input_schema = pa.schema([("id", pa.int64()), ("shipping", pa.struct([("zip", pa.string())]))]) + df = pa.Table.from_pylist([{"id": 1, "shipping": {"zip": "1011"}}, {"id": 2, "shipping": None}], schema=input_schema) + expected = [ + {"id": 1, "region": None, "shipping": {"country": None, "zip": "1011"}, "billing": None}, + {"id": 2, "region": None, "shipping": None, "billing": None}, + ] + sources = ["region", "shipping.country", "billing.country"] + transforms: list[IdentityTransform[str] | BucketTransform[str]] = [IdentityTransform(), BucketTransform(4)] + cases = [(source_name, transform) for source_name in sources for transform in transforms] + for i, (source_name, transform) in enumerate(cases): + tbl = catalog.create_table(f"default.missing_partition_source_{i}", schema=table_schema) + with tbl.update_spec() as update: + update.add_field(source_name, transform, "p") + + tbl.append(df) + + # The writer stores nulls for the missing columns, so the rows are in the null partition + assert sorted(tbl.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == expected, (source_name, transform) + assert [task.file.partition[0] for task in tbl.scan().plan_files()] == [None], (source_name, transform) + assert tbl.scan(row_filter=f"{source_name} IS NULL").to_arrow().num_rows == 2, (source_name, transform) + + def test_append_table(catalog: Catalog, table_schema_simple: Schema, test_table_identifier: Identifier) -> None: namespace = Catalog.namespace_from(test_table_identifier) catalog.create_namespace(namespace) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 1605dd3b67..b585ab943e 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -131,7 +131,15 @@ from pyiceberg.table.metadata_columns import LAST_UPDATED_SEQUENCE_NUMBER, ROW_ID from pyiceberg.table.name_mapping import create_mapping_from_schema from pyiceberg.table.puffin import MAGIC_BYTES, PuffinFile -from pyiceberg.transforms import BucketTransform, HourTransform, IdentityTransform, Transform, TruncateTransform, YearTransform +from pyiceberg.transforms import ( + BucketTransform, + DayTransform, + HourTransform, + IdentityTransform, + Transform, + TruncateTransform, + YearTransform, +) from pyiceberg.typedef import UTF8, Properties, Record, TableVersion from pyiceberg.types import ( BinaryType, @@ -4492,6 +4500,74 @@ 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_append_partitioned_ns_timestamp_downcast(monkeypatch: pytest.MonkeyPatch, catalog: InMemoryCatalog) -> None: + monkeypatch.setenv("PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE", "True") + catalog.create_namespace("default") + # Stored as [1, 1, 0, 3600000000, null] us: 1000 and 1500 ns share 1 us, and -1 ns becomes 0 us + values = [1000, 1500, -1, 3600000000000, None] + cases: list[tuple[Transform[Any, Any], PrimitiveType, str | None, dict[Any, int]]] = [ + (IdentityTransform(), TimestampType(), None, {1: 2, 0: 1, 3600000000: 1, None: 1}), + (HourTransform(), TimestampType(), None, {0: 3, 1: 1, None: 1}), + (DayTransform(), TimestamptzType(), "UTC", {0: 4, None: 1}), + ] + for transform, ts_type, tz, expected in cases: + table = catalog.create_table( + f"default.ns_downcast_{transform}", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "ts", ts_type, required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, transform, name="ts_part")), + ) + table.append(pa.table({"id": pa.array(range(5), pa.int64()), "ts": pa.array(values, pa.timestamp("ns", tz=tz))})) + + rows = table.scan().to_arrow().sort_by("id") + assert rows.column("id").to_pylist() == [0, 1, 2, 3, 4], transform + assert rows.column("ts").cast(pa.int64()).to_pylist() == [1, 1, 0, 3600000000, None], transform + assert {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} == expected, transform + + +def test_append_partitioned_ns_time_downcast(monkeypatch: pytest.MonkeyPatch, catalog: InMemoryCatalog) -> None: + monkeypatch.setenv("PYICEBERG_DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE", "True") + catalog.create_namespace("default") + table = catalog.create_table( + "default.ns_time_downcast", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "t", TimeType(), required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, IdentityTransform(), name="t_part")), + ) + # Stored as [1, 1, 3600000001, null] us: 1000 and 1500 ns share 1 us, and 3600000001500 ns is alone in its us + values = [1000, 1500, 3600000001500, None] + table.append(pa.table({"id": pa.array(range(4), pa.int64()), "t": pa.array(values, pa.time64("ns"))})) + + rows = table.scan().to_arrow().sort_by("id") + assert rows.column("id").to_pylist() == [0, 1, 2, 3] + assert rows.column("t").cast(pa.int64()).to_pylist() == [1, 1, 3600000001, None] + partitions = {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} + assert partitions == {1: 2, 3600000001: 1, None: 1} + + +def test_append_partitioned_float16_is_widened(catalog: InMemoryCatalog) -> None: + catalog.create_namespace("default") + table = catalog.create_table( + "default.float16_partition", + schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "v", FloatType(), required=False)), + partition_spec=PartitionSpec(PartitionField(2, 1000, IdentityTransform(), name="v_part")), + ) + table.append(pa.table({"id": pa.array([0, 1, 2], pa.int64()), "v": pa.array([1.5, 0.25, 1.5], pa.float16())})) + + assert table.scan().to_arrow().sort_by("id").column("v").to_pylist() == [1.5, 0.25, 1.5] + assert {task.file.partition[0]: task.file.record_count for task in table.scan().plan_files()} == {1.5: 2, 0.25: 1} + + +def test_determine_partitions_native_ns_timestamp_is_not_downcast() -> None: + # v3 nanosecond sources keep their precision, so day(-1 ns) stays -1 even with the downcast flag on + for source_type, tz in [(TimestampNanoType(), None), (TimestamptzNanoType(), "UTC")]: + schema = Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "ts", source_type, required=False)) + spec = PartitionSpec(PartitionField(2, 1000, DayTransform(), name="ts_day")) + arrow_table = pa.table({"id": pa.array([0, 1], pa.int64()), "ts": pa.array([-1, None], pa.timestamp("ns", tz=tz))}) + result = _determine_partitions(spec, schema, arrow_table, downcast_ns_timestamp_to_us=True) + assert { + p.partition_key.partition[0]: p.arrow_table_partition.column("ts").cast(pa.int64()).to_pylist() for p in result + } == {-1: [-1], None: [None]}, source_type + + 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))