From 8d06368732f80f5e2f002aaf8252b3538251f217 Mon Sep 17 00:00:00 2001 From: linzch3 <20380442+linzch3@users.noreply.github.com> Date: Wed, 18 Nov 2026 13:18:59 +0000 Subject: [PATCH 1/4] Use field IDs when any Parquet column has one _HasIds previously required every column to have an ID. A file with IDs on only some columns, such as a Databricks UniForm table with row-tracking columns, fell back to name mapping and failed when physical names differed from the mapped names. Match Java's ParquetSchemaUtil.hasIds (any) and prune fields without IDs, including incomplete nested types. --- pyiceberg/io/pyarrow.py | 58 ++++++++++++++++++------------ tests/io/test_pyarrow.py | 6 ++-- tests/io/test_pyarrow_visitor.py | 62 +++++++++++++++++++++++++++++--- 3 files changed, 98 insertions(+), 28 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index f5ddaee8f4..b55cf710c8 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1300,9 +1300,11 @@ def pyarrow_to_schema( ) -> Schema: has_ids = visit_pyarrow(schema, _HasIds()) if has_ids: - return visit_pyarrow( + result = visit_pyarrow( schema, _ConvertToIceberg(downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version) ) + assert isinstance(result, Schema) + return result elif name_mapping is not None: schema_without_ids = _pyarrow_to_schema_without_ids( schema, downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version @@ -1319,10 +1321,12 @@ def _pyarrow_to_schema_without_ids( downcast_ns_timestamp_to_us: bool = False, format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION, ) -> Schema: - return visit_pyarrow( + result = visit_pyarrow( schema, _ConvertToIcebergWithoutIDs(downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version), ) + assert isinstance(result, Schema) + return result def _pyarrow_schema_ensure_large_types(schema: pa.Schema) -> pa.Schema: @@ -1480,29 +1484,36 @@ def _get_field_id(field: pa.Field) -> int | None: class _HasIds(PyArrowSchemaVisitor[bool]): + """Return whether any field in the Arrow schema has an Iceberg field ID. + + Matches Java's ParquetSchemaUtil.hasIds, which is true if any column has an ID. + Fields without IDs are later pruned by _ConvertToIceberg. + """ + def schema(self, schema: pa.Schema, struct_result: bool) -> bool: return struct_result def struct(self, struct: pa.StructType, field_results: builtins.list[bool]) -> bool: - return all(field_results) + return any(field_results) def field(self, field: pa.Field, field_result: bool) -> bool: - return all([_get_field_id(field) is not None, field_result]) + return _get_field_id(field) is not None or field_result def list(self, list_type: pa.ListType, element_result: bool) -> bool: element_field = list_type.value_field element_id = _get_field_id(element_field) - return element_result and element_id is not None + return element_result or element_id is not None def map(self, map_type: pa.MapType, key_result: bool, value_result: bool) -> bool: key_field = map_type.key_field key_id = _get_field_id(key_field) value_field = map_type.item_field value_id = _get_field_id(value_field) - return all([key_id is not None, value_id is not None, key_result, value_result]) + return any([key_id is not None, value_id is not None, key_result, value_result]) def primitive(self, primitive: pa.DataType) -> bool: - return True + # IDs live on pa.Field metadata, not on primitive types + return False def _geoarrow_crs_to_iceberg(crs: object) -> str: @@ -1549,7 +1560,7 @@ def _geoarrow_crs_to_iceberg(crs: object) -> str: return crs -class _ConvertToIceberg(PyArrowSchemaVisitor[IcebergType | Schema]): +class _ConvertToIceberg(PyArrowSchemaVisitor[IcebergType | Schema | None]): """Converts PyArrowSchema to Iceberg Schema.""" _field_names: builtins.list[str] @@ -1561,34 +1572,37 @@ def __init__( self._downcast_ns_timestamp_to_us = downcast_ns_timestamp_to_us self._format_version = format_version - def _field_id(self, field: pa.Field) -> int: - if (field_id := _get_field_id(field)) is not None: - return field_id - else: - raise ValueError(f"Cannot convert {field} to Iceberg Field as field_id is empty.") + def _field_id(self, field: pa.Field) -> int | None: + return _get_field_id(field) - def schema(self, schema: pa.Schema, struct_result: StructType) -> Schema: - return Schema(*struct_result.fields) + def schema(self, schema: pa.Schema, struct_result: StructType | None) -> Schema: + return Schema(*(struct_result.fields if struct_result is not None else ())) - def struct(self, struct: pa.StructType, field_results: builtins.list[NestedField]) -> StructType: - return StructType(*field_results) + def struct(self, struct: pa.StructType, field_results: builtins.list[NestedField | None]) -> StructType | None: + fields = tuple(field for field in field_results if field is not None) + return StructType(*fields) if fields else None - def field(self, field: pa.Field, field_result: IcebergType) -> NestedField: + def field(self, field: pa.Field, field_result: IcebergType | None) -> NestedField | None: field_id = self._field_id(field) + if field_id is None or field_result is None: + return None field_doc = doc_str.decode() if (field.metadata and (doc_str := field.metadata.get(PYARROW_FIELD_DOC_KEY))) else None - field_type = field_result - return NestedField(field_id, field.name, field_type, required=not field.nullable, doc=field_doc) + return NestedField(field_id, field.name, field_result, required=not field.nullable, doc=field_doc) - def list(self, list_type: pa.ListType, element_result: IcebergType) -> ListType: + def list(self, list_type: pa.ListType, element_result: IcebergType | None) -> ListType | None: element_field = list_type.value_field element_id = self._field_id(element_field) + if element_id is None or element_result is None: + return None return ListType(element_id, element_result, element_required=not element_field.nullable) - def map(self, map_type: pa.MapType, key_result: IcebergType, value_result: IcebergType) -> MapType: + def map(self, map_type: pa.MapType, key_result: IcebergType | None, value_result: IcebergType | None) -> MapType | None: key_field = map_type.key_field key_id = self._field_id(key_field) value_field = map_type.item_field value_id = self._field_id(value_field) + if key_id is None or value_id is None or key_result is None or value_result is None: + return None return MapType(key_id, key_result, value_id, value_result, value_required=not value_field.nullable) def primitive(self, primitive: pa.DataType) -> PrimitiveType: diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 5c1933fc20..22b416b2d4 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3338,10 +3338,11 @@ def test_schema_compatible_missing_nullable_field_nested(table_schema_nested: Sc "person", pa.struct( [ - pa.field("age", pa.int32(), nullable=False), + pa.field("age", pa.int32(), nullable=False, metadata={"PARQUET:field_id": "17"}), ] ), nullable=True, + metadata={"PARQUET:field_id": "15"}, ), ) try: @@ -3359,10 +3360,11 @@ def test_schema_mismatch_missing_required_field_nested(table_schema_nested: Sche "person", pa.struct( [ - pa.field("name", pa.string(), nullable=True), + pa.field("name", pa.string(), nullable=True, metadata={"PARQUET:field_id": "16"}), ] ), nullable=True, + metadata={"PARQUET:field_id": "15"}, ), ) expected = """Mismatch in fields: diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py index 23b2b0d685..6bc9d40542 100644 --- a/tests/io/test_pyarrow_visitor.py +++ b/tests/io/test_pyarrow_visitor.py @@ -613,7 +613,7 @@ def test_simple_schema_has_missing_ids() -> None: assert not has_ids -def test_simple_schema_has_missing_ids_partial() -> None: +def test_simple_schema_has_partial_ids() -> None: schema = pa.schema( [ pa.field("foo", pa.string(), nullable=False, metadata={"PARQUET:field_id": "1", "doc": "foo doc"}), @@ -622,7 +622,7 @@ def test_simple_schema_has_missing_ids_partial() -> None: ) visitor = _HasIds() has_ids = visit_pyarrow(schema, visitor) - assert not has_ids + assert has_ids def test_nested_schema_has_missing_ids() -> None: @@ -672,7 +672,7 @@ def test_nested_schema_has_ids() -> None: assert has_ids -def test_nested_schema_has_partial_missing_ids() -> None: +def test_nested_schema_has_partial_ids() -> None: schema = pa.schema( [ pa.field("foo", pa.string(), nullable=False, metadata={"PARQUET:field_id": "1", "doc": "foo doc"}), @@ -693,7 +693,61 @@ def test_nested_schema_has_partial_missing_ids() -> None: ) visitor = _HasIds() has_ids = visit_pyarrow(schema, visitor) - assert not has_ids + assert has_ids + + +def test_pyarrow_to_schema_prunes_fields_without_ids() -> None: + # A Databricks UniForm file may attach IDs only to data columns, leaving + # row-tracking columns unannotated. Previously _HasIds required every + # column to have an ID and fell back to name mapping, which failed when + # physical names differed from the mapped names. + file_schema = pa.schema( + [ + pa.field("col-2b93b371", pa.string(), metadata={"PARQUET:field_id": "1"}), + pa.field("_row-id-col-922d6355", pa.int64()), + ] + ) + expected = Schema(NestedField(1, "col-2b93b371", StringType(), required=False)) + name_mappings = [None, NameMapping([MappedField(field_id=1, names=["store_id"])])] + for name_mapping in name_mappings: + assert pyarrow_to_schema(file_schema, name_mapping) == expected + + +def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: + schema = pa.schema( + [ + pa.field("foo", pa.string(), nullable=False, metadata={"PARQUET:field_id": "1", "doc": "foo doc"}), + pa.field( + "quux", + pa.map_( + pa.field("key", pa.string(), nullable=False, metadata={"PARQUET:field_id": "7"}), + pa.field( + "value", + pa.map_(pa.field("key", pa.string(), nullable=False), pa.field("value", pa.int32())), + nullable=False, + ), + ), + nullable=False, + metadata={"PARQUET:field_id": "6", "doc": "quux doc"}, + ), + pa.field( + "person", + pa.struct( + [ + pa.field("name", pa.string(), metadata={"PARQUET:field_id": "16"}), + pa.field("age", pa.int32()), + ] + ), + metadata={"PARQUET:field_id": "15"}, + ), + ] + ) + actual = str(pyarrow_to_schema(schema)) + expected = """table { + 1: foo: required string (foo doc) + 15: person: optional struct<16: name: optional string> +}""" + assert actual == expected def test_pyarrow_schema_to_schema_missing_ids_and_name_mapping(pyarrow_schema_simple_without_ids: pa.Schema) -> None: From dcc97623427178bd1f1303cc484a55fd02c06a7d Mon Sep 17 00:00:00 2001 From: linzch3 <20380442+linzch3@users.noreply.github.com> Date: Thu, 19 Nov 2026 03:05:52 +0000 Subject: [PATCH 2/4] Prune fields without IDs only when reading data files Review feedback: keep the old behavior on the write path, so an append with an extra column that has no field ID is still rejected instead of silently dropping that column. _HasIds and _ConvertToIceberg are back to their previous behavior. pyarrow_to_schema gets a prune_fields_without_ids flag, used only when reading data files. It drops fields without IDs from the Arrow schema before conversion, so an unsupported type in such a column (e.g. time32[ms]) does not fail the read. Lists without an element ID and maps without a key or value ID are dropped as a whole. Add tests for the list element / map key / map value ID guards, the pre-conversion pruning, a read of a file with partial IDs, and the append rejection. --- pyiceberg/io/pyarrow.py | 127 ++++++++++++++++++++++--------- tests/io/test_pyarrow.py | 41 +++++++++- tests/io/test_pyarrow_visitor.py | 118 ++++++++++++++++++++++++---- 3 files changed, 232 insertions(+), 54 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index b55cf710c8..4244e456c3 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1297,14 +1297,31 @@ def pyarrow_to_schema( name_mapping: NameMapping | None = None, downcast_ns_timestamp_to_us: bool = False, format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION, + prune_fields_without_ids: bool = False, ) -> Schema: + """Convert a PyArrow schema to an Iceberg schema. + + Args: + schema: The PyArrow schema to convert. + name_mapping: Used when the schema has no field IDs. + downcast_ns_timestamp_to_us: Downcast nanosecond timestamps to microseconds. + format_version: The Iceberg table format version. + prune_fields_without_ids: If some fields have field IDs, drop the ones that do not + (including lists and maps with an element, key, or value without one) instead of + falling back to the name mapping, like the Java Parquet reader does. Only meant for + reading data files. Writes keep the stricter check, so extra columns are rejected + instead of silently dropped. + """ + if prune_fields_without_ids: + # Prune before conversion, so an unsupported type in a column without an ID does not fail the read + pruned_schema = _prune_fields_without_ids(schema) + if len(pruned_schema) > 0: + schema = pruned_schema has_ids = visit_pyarrow(schema, _HasIds()) if has_ids: - result = visit_pyarrow( + return visit_pyarrow( schema, _ConvertToIceberg(downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version) ) - assert isinstance(result, Schema) - return result elif name_mapping is not None: schema_without_ids = _pyarrow_to_schema_without_ids( schema, downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version @@ -1316,17 +1333,59 @@ def pyarrow_to_schema( ) +def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema: + """Drop fields without a field ID, so only the columns with IDs are read. + + A list is dropped when its element has no ID, and a map when its key or value has none, + since neither can be represented in Iceberg without them. A struct whose children all + get dropped is dropped as well. + """ + fields = [pruned for field in schema if (pruned := _prune_field_without_id(field)) is not None] + return pa.schema(fields, metadata=schema.metadata) + + +def _prune_field_without_id(field: pa.Field) -> pa.Field | None: + if _get_field_id(field) is None: + return None + pruned_type = _prune_type_without_ids(field.type) + if pruned_type is None: + return None + return field.with_type(pruned_type) + + +def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None: + if pa.types.is_struct(arrow_type): + children = [arrow_type.field(i) for i in range(arrow_type.num_fields)] + pruned_children = [pruned for child in children if (pruned := _prune_field_without_id(child)) is not None] + return pa.struct(pruned_children) if pruned_children else None + elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + element_field = _prune_field_without_id(arrow_type.value_field) + if element_field is None: + return None + if isinstance(arrow_type, pa.LargeListType): + return pa.large_list(element_field) + if isinstance(arrow_type, pa.FixedSizeListType): + return pa.list_(element_field, arrow_type.list_size) + return pa.list_(element_field) + elif isinstance(arrow_type, pa.MapType): + key_field = _prune_field_without_id(arrow_type.key_field) + value_field = _prune_field_without_id(arrow_type.item_field) + if key_field is None or value_field is None: + # Keeping a map without its value (or key) would change its type, so drop the whole map + return None + return pa.map_(key_field, value_field, keys_sorted=arrow_type.keys_sorted) + return arrow_type + + def _pyarrow_to_schema_without_ids( schema: pa.Schema, downcast_ns_timestamp_to_us: bool = False, format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION, ) -> Schema: - result = visit_pyarrow( + return visit_pyarrow( schema, _ConvertToIcebergWithoutIDs(downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version), ) - assert isinstance(result, Schema) - return result def _pyarrow_schema_ensure_large_types(schema: pa.Schema) -> pa.Schema: @@ -1484,36 +1543,29 @@ def _get_field_id(field: pa.Field) -> int | None: class _HasIds(PyArrowSchemaVisitor[bool]): - """Return whether any field in the Arrow schema has an Iceberg field ID. - - Matches Java's ParquetSchemaUtil.hasIds, which is true if any column has an ID. - Fields without IDs are later pruned by _ConvertToIceberg. - """ - def schema(self, schema: pa.Schema, struct_result: bool) -> bool: return struct_result def struct(self, struct: pa.StructType, field_results: builtins.list[bool]) -> bool: - return any(field_results) + return all(field_results) def field(self, field: pa.Field, field_result: bool) -> bool: - return _get_field_id(field) is not None or field_result + return all([_get_field_id(field) is not None, field_result]) def list(self, list_type: pa.ListType, element_result: bool) -> bool: element_field = list_type.value_field element_id = _get_field_id(element_field) - return element_result or element_id is not None + return element_result and element_id is not None def map(self, map_type: pa.MapType, key_result: bool, value_result: bool) -> bool: key_field = map_type.key_field key_id = _get_field_id(key_field) value_field = map_type.item_field value_id = _get_field_id(value_field) - return any([key_id is not None, value_id is not None, key_result, value_result]) + return all([key_id is not None, value_id is not None, key_result, value_result]) def primitive(self, primitive: pa.DataType) -> bool: - # IDs live on pa.Field metadata, not on primitive types - return False + return True def _geoarrow_crs_to_iceberg(crs: object) -> str: @@ -1560,7 +1612,7 @@ def _geoarrow_crs_to_iceberg(crs: object) -> str: return crs -class _ConvertToIceberg(PyArrowSchemaVisitor[IcebergType | Schema | None]): +class _ConvertToIceberg(PyArrowSchemaVisitor[IcebergType | Schema]): """Converts PyArrowSchema to Iceberg Schema.""" _field_names: builtins.list[str] @@ -1572,37 +1624,34 @@ def __init__( self._downcast_ns_timestamp_to_us = downcast_ns_timestamp_to_us self._format_version = format_version - def _field_id(self, field: pa.Field) -> int | None: - return _get_field_id(field) + def _field_id(self, field: pa.Field) -> int: + if (field_id := _get_field_id(field)) is not None: + return field_id + else: + raise ValueError(f"Cannot convert {field} to Iceberg Field as field_id is empty.") - def schema(self, schema: pa.Schema, struct_result: StructType | None) -> Schema: - return Schema(*(struct_result.fields if struct_result is not None else ())) + def schema(self, schema: pa.Schema, struct_result: StructType) -> Schema: + return Schema(*struct_result.fields) - def struct(self, struct: pa.StructType, field_results: builtins.list[NestedField | None]) -> StructType | None: - fields = tuple(field for field in field_results if field is not None) - return StructType(*fields) if fields else None + def struct(self, struct: pa.StructType, field_results: builtins.list[NestedField]) -> StructType: + return StructType(*field_results) - def field(self, field: pa.Field, field_result: IcebergType | None) -> NestedField | None: + def field(self, field: pa.Field, field_result: IcebergType) -> NestedField: field_id = self._field_id(field) - if field_id is None or field_result is None: - return None field_doc = doc_str.decode() if (field.metadata and (doc_str := field.metadata.get(PYARROW_FIELD_DOC_KEY))) else None - return NestedField(field_id, field.name, field_result, required=not field.nullable, doc=field_doc) + field_type = field_result + return NestedField(field_id, field.name, field_type, required=not field.nullable, doc=field_doc) - def list(self, list_type: pa.ListType, element_result: IcebergType | None) -> ListType | None: + def list(self, list_type: pa.ListType, element_result: IcebergType) -> ListType: element_field = list_type.value_field element_id = self._field_id(element_field) - if element_id is None or element_result is None: - return None return ListType(element_id, element_result, element_required=not element_field.nullable) - def map(self, map_type: pa.MapType, key_result: IcebergType | None, value_result: IcebergType | None) -> MapType | None: + def map(self, map_type: pa.MapType, key_result: IcebergType, value_result: IcebergType) -> MapType: key_field = map_type.key_field key_id = self._field_id(key_field) value_field = map_type.item_field value_id = self._field_id(value_field) - if key_id is None or value_id is None or key_result is None or value_result is None: - return None return MapType(key_id, key_result, value_id, value_result, value_required=not value_field.nullable) def primitive(self, primitive: pa.DataType) -> PrimitiveType: @@ -1898,7 +1947,11 @@ def _task_to_record_batches( downcast_ns_timestamp_to_us if downcast_ns_timestamp_to_us is not None else format_version <= 2 ) file_schema = pyarrow_to_schema( - physical_schema, name_mapping, downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, format_version=format_version + physical_schema, + name_mapping, + downcast_ns_timestamp_to_us=downcast_ns_timestamp_to_us, + format_version=format_version, + prune_fields_without_ids=True, ) # Apply column projection rules: https://iceberg.apache.org/spec/#column-projection diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 22b416b2d4..04daf697f3 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -3338,11 +3338,10 @@ def test_schema_compatible_missing_nullable_field_nested(table_schema_nested: Sc "person", pa.struct( [ - pa.field("age", pa.int32(), nullable=False, metadata={"PARQUET:field_id": "17"}), + pa.field("age", pa.int32(), nullable=False), ] ), nullable=True, - metadata={"PARQUET:field_id": "15"}, ), ) try: @@ -3360,11 +3359,10 @@ def test_schema_mismatch_missing_required_field_nested(table_schema_nested: Sche "person", pa.struct( [ - pa.field("name", pa.string(), nullable=True, metadata={"PARQUET:field_id": "16"}), + pa.field("name", pa.string(), nullable=True), ] ), nullable=True, - metadata={"PARQUET:field_id": "15"}, ), ) expected = """Mismatch in fields: @@ -3427,6 +3425,41 @@ def test_schema_mismatch_additional_field(table_schema_simple: Schema) -> None: _check_pyarrow_schema_compatible(table_schema_simple, other_schema) +def test_schema_mismatch_additional_field_without_id(table_schema_simple: Schema) -> None: + # Appending a table read from a data file (with field IDs) plus a new column without one + # must still be rejected, rather than dropping the new column + other_schema = pa.schema( + ( + pa.field("foo", pa.string(), nullable=True, metadata={"PARQUET:field_id": "1"}), + pa.field("bar", pa.int32(), nullable=False, metadata={"PARQUET:field_id": "2"}), + pa.field("baz", pa.bool_(), nullable=True, metadata={"PARQUET:field_id": "3"}), + pa.field("country", pa.string(), nullable=True), + ) + ) + + with pytest.raises( + ValueError, match=r"PyArrow table contains more columns: country. Update the schema first \(hint, use union_by_name\)." + ): + _check_pyarrow_schema_compatible(table_schema_simple, other_schema) + + +def test_projection_partial_field_ids(tmpdir: str) -> None: + # Columns without a field ID are ignored on read, even if their type is not supported + schema = Schema(NestedField(1, "foo", StringType(), required=False)) + arrow_schema = pa.schema( + [ + pa.field("col-2b93b371", pa.string(), metadata={"PARQUET:field_id": "1"}), + pa.field("_row-id-col-922d6355", pa.time32("ms")), + ] + ) + table = pa.Table.from_arrays([pa.array(["a", "b", "c"]), pa.array([1, 2, 3], type=pa.time32("ms"))], schema=arrow_schema) + file = _write_table_to_file(f"{tmpdir}/partial-ids.parquet", arrow_schema, table) + + result = project(schema, [file]) + assert result.column_names == ["foo"] + assert result["foo"].to_pylist() == ["a", "b", "c"] + + def test_schema_compatible(table_schema_simple: Schema) -> None: try: _check_pyarrow_schema_compatible(table_schema_simple, table_schema_simple.as_arrow()) diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py index 6bc9d40542..8126e094e6 100644 --- a/tests/io/test_pyarrow_visitor.py +++ b/tests/io/test_pyarrow_visitor.py @@ -613,7 +613,7 @@ def test_simple_schema_has_missing_ids() -> None: assert not has_ids -def test_simple_schema_has_partial_ids() -> None: +def test_simple_schema_has_missing_ids_partial() -> None: schema = pa.schema( [ pa.field("foo", pa.string(), nullable=False, metadata={"PARQUET:field_id": "1", "doc": "foo doc"}), @@ -622,7 +622,7 @@ def test_simple_schema_has_partial_ids() -> None: ) visitor = _HasIds() has_ids = visit_pyarrow(schema, visitor) - assert has_ids + assert not has_ids def test_nested_schema_has_missing_ids() -> None: @@ -672,7 +672,7 @@ def test_nested_schema_has_ids() -> None: assert has_ids -def test_nested_schema_has_partial_ids() -> None: +def test_nested_schema_has_partial_missing_ids() -> None: schema = pa.schema( [ pa.field("foo", pa.string(), nullable=False, metadata={"PARQUET:field_id": "1", "doc": "foo doc"}), @@ -693,24 +693,51 @@ def test_nested_schema_has_partial_ids() -> None: ) visitor = _HasIds() has_ids = visit_pyarrow(schema, visitor) - assert has_ids + assert not has_ids + + +def _id(field_id: int) -> dict[str, str]: + return {"PARQUET:field_id": str(field_id)} def test_pyarrow_to_schema_prunes_fields_without_ids() -> None: # A Databricks UniForm file may attach IDs only to data columns, leaving - # row-tracking columns unannotated. Previously _HasIds required every - # column to have an ID and fell back to name mapping, which failed when - # physical names differed from the mapped names. + # row-tracking columns unannotated. Without pruning, the file falls back to + # name mapping, which fails when physical names differ from the mapped names. file_schema = pa.schema( [ - pa.field("col-2b93b371", pa.string(), metadata={"PARQUET:field_id": "1"}), + pa.field("col-2b93b371", pa.string(), metadata=_id(1)), pa.field("_row-id-col-922d6355", pa.int64()), ] ) expected = Schema(NestedField(1, "col-2b93b371", StringType(), required=False)) name_mappings = [None, NameMapping([MappedField(field_id=1, names=["store_id"])])] for name_mapping in name_mappings: - assert pyarrow_to_schema(file_schema, name_mapping) == expected + assert pyarrow_to_schema(file_schema, name_mapping, prune_fields_without_ids=True) == expected + + +def test_pyarrow_to_schema_partial_ids_without_pruning() -> None: + # Without pruning (e.g. on write), partial IDs still fall back to the name mapping + file_schema = pa.schema( + [ + pa.field("foo", pa.string(), metadata=_id(1)), + pa.field("bar", pa.int64()), + ] + ) + with pytest.raises(ValueError, match="Parquet file does not have field-ids"): + pyarrow_to_schema(file_schema) + + +def test_pyarrow_to_schema_prunes_before_type_conversion() -> None: + # time32[ms] is not supported, but the column has no ID so it is never read + file_schema = pa.schema( + [ + pa.field("foo", pa.string(), metadata=_id(1)), + pa.field("bar", pa.time32("ms")), + ] + ) + expected = Schema(NestedField(1, "foo", StringType(), required=False)) + assert pyarrow_to_schema(file_schema, prune_fields_without_ids=True) == expected def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: @@ -720,7 +747,7 @@ def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: pa.field( "quux", pa.map_( - pa.field("key", pa.string(), nullable=False, metadata={"PARQUET:field_id": "7"}), + pa.field("key", pa.string(), nullable=False, metadata=_id(7)), pa.field( "value", pa.map_(pa.field("key", pa.string(), nullable=False), pa.field("value", pa.int32())), @@ -734,15 +761,15 @@ def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: "person", pa.struct( [ - pa.field("name", pa.string(), metadata={"PARQUET:field_id": "16"}), + pa.field("name", pa.string(), metadata=_id(16)), pa.field("age", pa.int32()), ] ), - metadata={"PARQUET:field_id": "15"}, + metadata=_id(15), ), ] ) - actual = str(pyarrow_to_schema(schema)) + actual = str(pyarrow_to_schema(schema, prune_fields_without_ids=True)) expected = """table { 1: foo: required string (foo doc) 15: person: optional struct<16: name: optional string> @@ -750,6 +777,71 @@ def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: assert actual == expected +def test_pyarrow_to_schema_prunes_list_without_element_id() -> None: + schema = pa.schema( + [ + pa.field("foo", pa.string(), metadata=_id(1)), + pa.field("no_element_id", pa.list_(pa.field("element", pa.int32())), metadata=_id(2)), + pa.field("with_element_id", pa.list_(pa.field("element", pa.int32(), metadata=_id(4))), metadata=_id(3)), + ] + ) + expected = Schema( + NestedField(1, "foo", StringType(), required=False), + NestedField(3, "with_element_id", ListType(4, IntegerType(), element_required=False), required=False), + ) + assert pyarrow_to_schema(schema, prune_fields_without_ids=True) == expected + + +@pytest.mark.parametrize( + "key_metadata, value_metadata", + [ + (None, _id(4)), # value only + (_id(3), None), # key only, the value can't be kept on its own so the whole map goes + ], +) +def test_pyarrow_to_schema_prunes_map_without_key_or_value_id( + key_metadata: dict[str, str] | None, value_metadata: dict[str, str] | None +) -> None: + schema = pa.schema( + [ + pa.field("foo", pa.string(), metadata=_id(1)), + pa.field( + "partial_map", + pa.map_( + pa.field("key", pa.string(), nullable=False, metadata=key_metadata), + pa.field("value", pa.int32(), metadata=value_metadata), + ), + metadata=_id(2), + ), + pa.field( + "full_map", + pa.map_( + pa.field("key", pa.string(), nullable=False, metadata=_id(6)), + pa.field("value", pa.int32(), metadata=_id(7)), + ), + metadata=_id(5), + ), + ] + ) + expected = Schema( + NestedField(1, "foo", StringType(), required=False), + NestedField( + 5, + "full_map", + MapType(key_id=6, key_type=StringType(), value_id=7, value_type=IntegerType(), value_required=False), + required=False, + ), + ) + assert pyarrow_to_schema(schema, prune_fields_without_ids=True) == expected + + +def test_pyarrow_to_schema_without_any_ids_uses_name_mapping_when_pruning() -> None: + schema = pa.schema([pa.field("foo", pa.string())]) + name_mapping = NameMapping([MappedField(field_id=1, names=["foo"])]) + expected = Schema(NestedField(1, "foo", StringType(), required=False)) + assert pyarrow_to_schema(schema, name_mapping, prune_fields_without_ids=True) == expected + + def test_pyarrow_schema_to_schema_missing_ids_and_name_mapping(pyarrow_schema_simple_without_ids: pa.Schema) -> None: schema = pyarrow_schema_simple_without_ids with pytest.raises(ValueError) as exc_info: From 1ac11dc3482f9bb66602c37c243c4c15f3d4c751 Mon Sep 17 00:00:00 2001 From: linzch3 <20380442+linzch3@users.noreply.github.com> Date: Wed, 25 Nov 2026 14:27:33 +0000 Subject: [PATCH 3/4] Reject partial field IDs in add_files and read by ID when any field has one add_files now rejects a Parquet file that has field IDs on only some of its columns, since the reader ignores the columns without one and would return null for them. On read, the fallback to the name mapping now depends on whether the file has any field IDs, not on whether anything is left after pruning, so a file whose only ID-carrying fields all get pruned is still read by ID. --- pyiceberg/io/pyarrow.py | 33 +++++++++++++++++++++++---- tests/io/test_pyarrow.py | 39 ++++++++++++++++++++++++++++++++ tests/io/test_pyarrow_visitor.py | 19 ++++++++++++++++ 3 files changed, 87 insertions(+), 4 deletions(-) diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index 4244e456c3..ef7dd8ab56 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1313,10 +1313,10 @@ def pyarrow_to_schema( instead of silently dropped. """ if prune_fields_without_ids: - # Prune before conversion, so an unsupported type in a column without an ID does not fail the read - pruned_schema = _prune_fields_without_ids(schema) - if len(pruned_schema) > 0: - schema = pruned_schema + # Prune before conversion, so an unsupported type in a column without an ID does not fail the read. + # Any field ID means the file is read by ID, even if every field ends up pruned. + if _has_any_field_ids(schema): + schema = _prune_fields_without_ids(schema) has_ids = visit_pyarrow(schema, _HasIds()) if has_ids: return visit_pyarrow( @@ -1333,6 +1333,24 @@ def pyarrow_to_schema( ) +def _has_any_field_ids(schema: pa.Schema) -> bool: + """Return whether any field in the schema, including nested ones, has a field ID.""" + return any(_field_has_any_ids(field) for field in schema) + + +def _field_has_any_ids(field: pa.Field) -> bool: + if _get_field_id(field) is not None: + return True + arrow_type = field.type + if pa.types.is_struct(arrow_type): + return any(_field_has_any_ids(arrow_type.field(i)) for i in range(arrow_type.num_fields)) + elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + return _field_has_any_ids(arrow_type.value_field) + elif isinstance(arrow_type, pa.MapType): + return _field_has_any_ids(arrow_type.key_field) or _field_has_any_ids(arrow_type.item_field) + return False + + def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema: """Drop fields without a field ID, so only the columns with IDs are read. @@ -3373,6 +3391,13 @@ def parquet_file_to_data_file(io: FileIO, table_metadata: TableMetadata, file_pa arrow_schema = parquet_metadata.schema.to_arrow_schema() + if _has_any_field_ids(arrow_schema) and not visit_pyarrow(arrow_schema, _HasIds()): + # The reader only reads the columns with field IDs, so the others would silently be read as null + raise ValueError( + f"Cannot add file {file_path}: it has field IDs on only some of its columns. " + "Columns without a field ID would be read as null." + ) + schema = table_metadata.schema() _check_pyarrow_schema_compatible(schema, arrow_schema, format_version=table_metadata.format_version) diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index 04daf697f3..a9a2107f8c 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -112,6 +112,7 @@ compute_statistics_plan, data_file_statistics_from_parquet_metadata, expression_to_pyarrow, + parquet_file_to_data_file, parquet_path_to_id_mapping, schema_to_pyarrow, visit_pyarrow, @@ -3460,6 +3461,44 @@ def test_projection_partial_field_ids(tmpdir: str) -> None: assert result["foo"].to_pylist() == ["a", "b", "c"] +@pytest.mark.parametrize( + "bar_metadata, rejected", + [ + ({"PARQUET:field_id": "2"}, False), # all columns have field IDs + (None, True), # only some columns have field IDs + ], +) +def test_parquet_file_to_data_file_partial_field_ids(tmp_path: Path, bar_metadata: dict[str, str] | None, rejected: bool) -> None: + # The reader ignores columns without a field ID, so add_files must not accept a file + # where only some columns have one, as those columns would be read as null + table_schema = Schema( + NestedField(1, "foo", StringType(), required=False), + NestedField(2, "bar", StringType(), required=False), + ) + arrow_schema = pa.schema( + [ + pa.field("foo", pa.string(), metadata={"PARQUET:field_id": "1"}), + pa.field("bar", pa.string(), metadata=bar_metadata), + ] + ) + table = pa.Table.from_arrays([pa.array(["a"]), pa.array(["from file"])], schema=arrow_schema) + file_path = _write_table_to_file(f"{tmp_path}/partial-ids.parquet", arrow_schema, table) + table_metadata = TableMetadataV2( + location=f"file://{tmp_path}", + last_column_id=2, + format_version=2, + schemas=[table_schema], + partition_specs=[PartitionSpec()], + ) + + if rejected: + with pytest.raises(ValueError, match="has field IDs on only some of its columns"): + parquet_file_to_data_file(io=PyArrowFileIO(), table_metadata=table_metadata, file_path=file_path) + else: + data_file = parquet_file_to_data_file(io=PyArrowFileIO(), table_metadata=table_metadata, file_path=file_path) + assert data_file.record_count == 1 + + def test_schema_compatible(table_schema_simple: Schema) -> None: try: _check_pyarrow_schema_compatible(table_schema_simple, table_schema_simple.as_arrow()) diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py index 8126e094e6..8a2c83158f 100644 --- a/tests/io/test_pyarrow_visitor.py +++ b/tests/io/test_pyarrow_visitor.py @@ -740,6 +740,25 @@ def test_pyarrow_to_schema_prunes_before_type_conversion() -> None: assert pyarrow_to_schema(file_schema, prune_fields_without_ids=True) == expected +def test_pyarrow_to_schema_reads_by_id_when_all_fields_pruned() -> None: + # The only ID is on a list whose element has none, so every field is pruned. The file + # still has field IDs, so it is read by ID (like with one more column with an ID) instead + # of falling back to the name mapping. + file_schema = pa.schema( + [ + pa.field("foo", pa.list_(pa.field("element", pa.int32())), metadata=_id(1)), + pa.field("bar", pa.string()), + ] + ) + name_mapping = NameMapping( + [ + MappedField(field_id=1, names=["foo"], fields=[MappedField(field_id=3, names=["element"])]), + MappedField(field_id=2, names=["bar"]), + ] + ) + assert pyarrow_to_schema(file_schema, name_mapping, prune_fields_without_ids=True) == Schema() + + def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: schema = pa.schema( [ From 112bce09507ee8c73e2068a6014474c97e6d31bd Mon Sep 17 00:00:00 2001 From: linzch3 <20380442+linzch3@users.noreply.github.com> Date: Mon, 30 Nov 2026 14:54:09 +0800 Subject: [PATCH 4/4] Keep maps with a field ID on only the key or value when reading Java's PruneColumns.map keeps the whole map when either child is selected, and TypeWithSchemaVisitor matches key and value by position. Do the same on the read path instead of dropping the map and returning null. Document that add_files rejects files with field IDs on only some columns, and add a test that IDs only on nested fields are detected. --- mkdocs/docs/api.md | 1 + pyiceberg/io/pyarrow.py | 128 ++++++++++++++++++++++++++++--- tests/io/test_pyarrow.py | 60 ++++++++++++++- tests/io/test_pyarrow_visitor.py | 77 +++++++++++++++---- 4 files changed, 241 insertions(+), 25 deletions(-) diff --git a/mkdocs/docs/api.md b/mkdocs/docs/api.md index 7eed8faa51..25742db2c2 100644 --- a/mkdocs/docs/api.md +++ b/mkdocs/docs/api.md @@ -1110,6 +1110,7 @@ Expert Iceberg users may choose to commit existing parquet files to the Iceberg `add_files` can work with Parquet files both with and without field IDs in their metadata: - **Files with field IDs**: When field IDs are present in the Parquet metadata, they must match the corresponding field IDs in the Iceberg table schema. This is common for files generated by tools like Spark or when using or other libraries with explicit field ID metadata. - **Files without field IDs**: When field IDs are absent, the table must have a [Name Mapping](https://iceberg.apache.org/spec/?h=name+mapping#name-mapping-serialization) to map field names to Iceberg field IDs. `add_files` will automatically create a Name Mapping based on the table's current schema if one doesn't already exist. + - **Files with field IDs on only some columns**: `add_files` rejects these files, because the reader ignores columns without a field ID and would return null for them. !!! note "Partitions" `add_files` only requires the client to read the existing parquet files' metadata footer to infer the partition value of each file. This implementation also supports adding files to Iceberg tables with partition transforms like `MonthTransform`, and `TruncateTransform` which preserve the order of the values after the transformation (Any Transform that has the `preserves_order` property set to True is supported). Please note that if the column statistics of the `PartitionField`'s source column are not present in the parquet metadata, the partition value is inferred as `None`. diff --git a/pyiceberg/io/pyarrow.py b/pyiceberg/io/pyarrow.py index ef7dd8ab56..5522f36b46 100644 --- a/pyiceberg/io/pyarrow.py +++ b/pyiceberg/io/pyarrow.py @@ -1307,8 +1307,9 @@ def pyarrow_to_schema( downcast_ns_timestamp_to_us: Downcast nanosecond timestamps to microseconds. format_version: The Iceberg table format version. prune_fields_without_ids: If some fields have field IDs, drop the ones that do not - (including lists and maps with an element, key, or value without one) instead of - falling back to the name mapping, like the Java Parquet reader does. Only meant for + (including lists whose element has no ID) instead of falling back to the name + mapping, like the Java Parquet reader does. A map is kept when either its key or + its value has an ID, and key and value are matched by position. Only meant for reading data files. Writes keep the stricter check, so extra columns are rejected instead of silently dropped. """ @@ -1354,11 +1355,16 @@ def _field_has_any_ids(field: pa.Field) -> bool: def _prune_fields_without_ids(schema: pa.Schema) -> pa.Schema: """Drop fields without a field ID, so only the columns with IDs are read. - A list is dropped when its element has no ID, and a map when its key or value has none, - since neither can be represented in Iceberg without them. A struct whose children all - get dropped is dropped as well. + A list is dropped when its element has no ID. A map is kept when its key or + value has an ID, including when only one side has one, matching Java's + PruneColumns.map; key and value are later matched by position. A struct + whose children all get dropped is dropped as well. """ fields = [pruned for field in schema if (pruned := _prune_field_without_id(field)) is not None] + # Placeholders let _ConvertToIceberg convert a kept map whose key or value has no ID. + # Projection matches map key and value by position, not by these IDs. + ids = itertools.count(-1, -1) + fields = [_assign_missing_field_ids(field, ids) for field in fields] return pa.schema(fields, metadata=schema.metadata) @@ -1386,15 +1392,118 @@ def _prune_type_without_ids(arrow_type: pa.DataType) -> pa.DataType | None: return pa.list_(element_field, arrow_type.list_size) return pa.list_(element_field) elif isinstance(arrow_type, pa.MapType): - key_field = _prune_field_without_id(arrow_type.key_field) - value_field = _prune_field_without_id(arrow_type.item_field) - if key_field is None or value_field is None: - # Keeping a map without its value (or key) would change its type, so drop the whole map + # Like Java's PruneColumns.map: keep the whole map when either child has any ID. + # TypeWithSchemaVisitor (and ArrowAccessor) later match key and value by position. + if not _field_has_any_ids(arrow_type.key_field) and not _field_has_any_ids(arrow_type.item_field): return None + key_field = _keep_map_child(arrow_type.key_field) + value_field = _keep_map_child(arrow_type.item_field) return pa.map_(key_field, value_field, keys_sorted=arrow_type.keys_sorted) return arrow_type +def _keep_map_child(field: pa.Field) -> pa.Field: + """Keep a map key or value so the map can be matched by position. + + If this side has an ID, still prune nested fields without one. If pruning + would drop the type, or this side itself has no ID, leave the field as-is; + missing IDs are filled in after the map is kept. + """ + if _get_field_id(field) is None: + return field + pruned_type = _prune_type_without_ids(field.type) + if pruned_type is None: + return field + return field.with_type(pruned_type) + + +def _assign_missing_field_ids(field: pa.Field, ids: Iterator[int]) -> pa.Field: + """Assign placeholder field IDs to any field that does not already have one.""" + metadata = dict(field.metadata or {}) + if _get_field_id(field) is None: + metadata[PYARROW_PARQUET_FIELD_ID_KEY] = str(next(ids)).encode() + new_type = _assign_missing_type_ids(field.type, ids) + return pa.field(field.name, new_type, nullable=field.nullable, metadata=metadata or None) + + +def _assign_missing_type_ids(arrow_type: pa.DataType, ids: Iterator[int]) -> pa.DataType: + if pa.types.is_struct(arrow_type): + children = [_assign_missing_field_ids(arrow_type.field(i), ids) for i in range(arrow_type.num_fields)] + return pa.struct(children) + elif isinstance(arrow_type, (pa.ListType, pa.LargeListType, pa.FixedSizeListType)): + element_field = _assign_missing_field_ids(arrow_type.value_field, ids) + if isinstance(arrow_type, pa.LargeListType): + return pa.large_list(element_field) + if isinstance(arrow_type, pa.FixedSizeListType): + return pa.list_(element_field, arrow_type.list_size) + return pa.list_(element_field) + elif isinstance(arrow_type, pa.MapType): + key_field = _assign_missing_field_ids(arrow_type.key_field, ids) + value_field = _assign_missing_field_ids(arrow_type.item_field, ids) + return pa.map_(key_field, value_field, keys_sorted=arrow_type.keys_sorted) + return arrow_type + + +def _align_map_key_value_ids(file_schema: Schema, table_schema: Schema) -> Schema: + """Match file map key/value IDs to the table schema by position. + + Java's TypeWithSchemaVisitor pairs a file map's key and value with the table + map's key and value by position, not by field ID. After pruning, a file map + may have a placeholder ID on the side that had no field ID; rewriting those + IDs here lets projection and filters find the table fields on the file schema. + """ + aligned = _align_iceberg_type(file_schema.as_struct(), table_schema.as_struct()) + if not isinstance(aligned, StructType) or aligned == file_schema.as_struct(): + return file_schema + return Schema( + *aligned.fields, + schema_id=file_schema.schema_id, + identifier_field_ids=list(file_schema.identifier_field_ids), + ) + + +def _align_iceberg_type(file_type: IcebergType, table_type: IcebergType) -> IcebergType: + if isinstance(file_type, MapType) and isinstance(table_type, MapType): + return MapType( + key_id=table_type.key_id, + key_type=_align_iceberg_type(file_type.key_type, table_type.key_type), + value_id=table_type.value_id, + value_type=_align_iceberg_type(file_type.value_type, table_type.value_type), + value_required=file_type.value_required, + ) + if isinstance(file_type, ListType) and isinstance(table_type, ListType): + return ListType( + element_id=file_type.element_id, + element_type=_align_iceberg_type(file_type.element_type, table_type.element_type), + element_required=file_type.element_required, + ) + if isinstance(file_type, StructType) and isinstance(table_type, StructType): + table_fields = {field.field_id: field for field in table_type.fields} + fields: list[NestedField] = [] + changed = False + for field in file_type.fields: + table_field = table_fields.get(field.field_id) + if table_field is None: + fields.append(field) + continue + new_type = _align_iceberg_type(field.field_type, table_field.field_type) + if new_type is field.field_type or new_type == field.field_type: + fields.append(field) + else: + changed = True + fields.append( + NestedField( + field_id=field.field_id, + name=field.name, + field_type=new_type, + required=field.required, + doc=field.doc, + ) + ) + return StructType(*fields) if changed else file_type + return file_type + + def _pyarrow_to_schema_without_ids( schema: pa.Schema, downcast_ns_timestamp_to_us: bool = False, @@ -1971,6 +2080,7 @@ def _task_to_record_batches( format_version=format_version, prune_fields_without_ids=True, ) + file_schema = _align_map_key_value_ids(file_schema, table_schema) # Apply column projection rules: https://iceberg.apache.org/spec/#column-projection projected_missing_fields = _get_column_projection_values( diff --git a/tests/io/test_pyarrow.py b/tests/io/test_pyarrow.py index a9a2107f8c..5705916125 100644 --- a/tests/io/test_pyarrow.py +++ b/tests/io/test_pyarrow.py @@ -130,7 +130,7 @@ ) from pyiceberg.table.metadata import TableMetadataV2, TableMetadataV3 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.name_mapping import NameMapping, create_mapping_from_schema from pyiceberg.table.puffin import MAGIC_BYTES, PuffinFile from pyiceberg.transforms import BucketTransform, HourTransform, IdentityTransform, Transform, TruncateTransform, YearTransform from pyiceberg.typedef import UTF8, Properties, Record, TableVersion @@ -1333,12 +1333,20 @@ def file_map(schema_map: Schema, tmpdir: str) -> str: def project( - schema: Schema, files: list[str], expr: BooleanExpression | None = None, table_schema: Schema | None = None + schema: Schema, + files: list[str], + expr: BooleanExpression | None = None, + table_schema: Schema | None = None, + name_mapping: NameMapping | None = None, ) -> pa.Table: def _set_spec_id(datafile: DataFile) -> DataFile: datafile.spec_id = 0 return datafile + properties: dict[str, str] = {} + if name_mapping is not None: + properties[TableProperties.DEFAULT_NAME_MAPPING] = name_mapping.model_dump_json() + return ArrowScan( table_metadata=TableMetadataV2( location="file://a/b/", @@ -1346,6 +1354,7 @@ def _set_spec_id(datafile: DataFile) -> DataFile: format_version=2, schemas=[table_schema or schema], partition_specs=[PartitionSpec()], + properties=properties, ), io=PyArrowFileIO(), projected_schema=schema, @@ -3444,6 +3453,53 @@ def test_schema_mismatch_additional_field_without_id(table_schema_simple: Schema _check_pyarrow_schema_compatible(table_schema_simple, other_schema) +@pytest.mark.parametrize( + "key_metadata, value_metadata, use_name_mapping", + [ + ({"PARQUET:field_id": "2"}, None, False), + ({"PARQUET:field_id": "2"}, None, True), + (None, {"PARQUET:field_id": "3"}, False), + (None, {"PARQUET:field_id": "3"}, True), + ], +) +def test_projection_map_with_id_on_key_or_value_only( + tmpdir: str, + key_metadata: dict[str, str] | None, + value_metadata: dict[str, str] | None, + use_name_mapping: bool, +) -> None: + # A map with an ID only on its key or only on its value is kept and read by + # position, like Java. A name mapping does not change the result once the file has IDs. + table_schema = Schema( + NestedField( + 1, + "foo", + MapType(key_id=2, key_type=StringType(), value_id=3, value_type=IntegerType(), value_required=False), + required=False, + ) + ) + arrow_schema = pa.schema( + [ + pa.field( + "foo", + pa.map_( + pa.field("key", pa.string(), nullable=False, metadata=key_metadata), + pa.field("value", pa.int32(), metadata=value_metadata), + ), + metadata={"PARQUET:field_id": "1"}, + ) + ] + ) + table = pa.Table.from_arrays( + [pa.array([[("k", 1)], [], None], type=arrow_schema.field("foo").type)], + schema=arrow_schema, + ) + file = _write_table_to_file(f"{tmpdir}/partial-map-ids.parquet", arrow_schema, table) + name_mapping = table_schema.name_mapping if use_name_mapping else None + result = project(table_schema, [file], name_mapping=name_mapping) + assert result["foo"].to_pylist() == [[("k", 1)], [], None] + + def test_projection_partial_field_ids(tmpdir: str) -> None: # Columns without a field ID are ignored on read, even if their type is not supported schema = Schema(NestedField(1, "foo", StringType(), required=False)) diff --git a/tests/io/test_pyarrow_visitor.py b/tests/io/test_pyarrow_visitor.py index 8a2c83158f..3cda71be30 100644 --- a/tests/io/test_pyarrow_visitor.py +++ b/tests/io/test_pyarrow_visitor.py @@ -41,6 +41,7 @@ _ConvertToIcebergWithoutIDs, _expression_to_complementary_pyarrow, _geoarrow_crs_to_iceberg, + _has_any_field_ids, _HasIds, _NullNaNUnmentionedTermsCollector, _pyarrow_schema_ensure_large_types, @@ -791,6 +792,7 @@ def test_pyarrow_to_schema_prunes_nested_fields_without_ids() -> None: actual = str(pyarrow_to_schema(schema, prune_fields_without_ids=True)) expected = """table { 1: foo: required string (foo doc) + 6: quux: required map> (quux doc) 15: person: optional struct<16: name: optional string> }""" assert actual == expected @@ -812,14 +814,17 @@ def test_pyarrow_to_schema_prunes_list_without_element_id() -> None: @pytest.mark.parametrize( - "key_metadata, value_metadata", + "key_metadata, value_metadata, expected_key_id, expected_value_id", [ - (None, _id(4)), # value only - (_id(3), None), # key only, the value can't be kept on its own so the whole map goes + (None, _id(4), None, 4), # value only; key gets a placeholder and is matched by position + (_id(3), None, 3, None), # key only; value gets a placeholder and is matched by position ], ) -def test_pyarrow_to_schema_prunes_map_without_key_or_value_id( - key_metadata: dict[str, str] | None, value_metadata: dict[str, str] | None +def test_pyarrow_to_schema_keeps_map_when_only_key_or_value_has_id( + key_metadata: dict[str, str] | None, + value_metadata: dict[str, str] | None, + expected_key_id: int | None, + expected_value_id: int | None, ) -> None: schema = pa.schema( [ @@ -842,16 +847,60 @@ def test_pyarrow_to_schema_prunes_map_without_key_or_value_id( ), ] ) - expected = Schema( - NestedField(1, "foo", StringType(), required=False), - NestedField( - 5, - "full_map", - MapType(key_id=6, key_type=StringType(), value_id=7, value_type=IntegerType(), value_required=False), - required=False, - ), + result = pyarrow_to_schema(schema, prune_fields_without_ids=True) + assert result.find_field(1) == NestedField(1, "foo", StringType(), required=False) + partial_map = result.find_field(2) + assert partial_map.name == "partial_map" + assert isinstance(partial_map.field_type, MapType) + if expected_key_id is not None: + assert partial_map.field_type.key_id == expected_key_id + else: + assert partial_map.field_type.key_id < 0 + if expected_value_id is not None: + assert partial_map.field_type.value_id == expected_value_id + else: + assert partial_map.field_type.value_id < 0 + assert partial_map.field_type.key_type == StringType() + assert partial_map.field_type.value_type == IntegerType() + assert result.find_field(5) == NestedField( + 5, + "full_map", + MapType(key_id=6, key_type=StringType(), value_id=7, value_type=IntegerType(), value_required=False), + required=False, ) - assert pyarrow_to_schema(schema, prune_fields_without_ids=True) == expected + + +def test_has_any_field_ids_detects_ids_only_on_nested_fields() -> None: + # IDs only on nested fields; a top-level-only check would miss these. + schema = pa.schema( + [ + pa.field( + "person", + pa.struct( + [ + pa.field("name", pa.string(), metadata=_id(2)), + pa.field("age", pa.int32()), + ] + ), + ), + pa.field("extra", pa.string()), + ] + ) + assert _has_any_field_ids(schema) + + # Because a nested field has an ID, the file is read by ID rather than the name mapping. + # The top-level fields themselves have no ID, so they are pruned. + name_mapping = NameMapping( + [ + MappedField( + field_id=1, + names=["person"], + fields=[MappedField(field_id=2, names=["name"]), MappedField(field_id=3, names=["age"])], + ), + MappedField(field_id=4, names=["extra"]), + ] + ) + assert pyarrow_to_schema(schema, name_mapping, prune_fields_without_ids=True) == Schema() def test_pyarrow_to_schema_without_any_ids_uses_name_mapping_when_pruning() -> None: