Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
19 changes: 17 additions & 2 deletions pyiceberg/io/pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,7 @@
SchemaVisitorPerPrimitiveType,
SchemaWithPartnerVisitor,
_check_schema_compatible,
_IndexByName,
build_position_accessors,
pre_order_visit,
promote,
Expand Down Expand Up @@ -3284,19 +3285,23 @@ def _check_pyarrow_schema_compatible(
provided_schema: pa.Schema,
downcast_ns_timestamp_to_us: bool = False,
format_version: TableVersion = TableProperties.DEFAULT_FORMAT_VERSION,
name_mapping: NameMapping | None = None,
) -> Schema:
"""
Check if the `requested_schema` is compatible with `provided_schema`.

Two schemas are considered compatible when they are equal in terms of the Iceberg Schema type.
If `provided_schema` lacks field IDs, its columns get them from `name_mapping`, which defaults to the names of
`requested_schema`.

Returns:
The Iceberg schema of `provided_schema`, with the field IDs of its columns.

Raises:
ValueError: If the schemas are not compatible.
"""
name_mapping = requested_schema.name_mapping
if name_mapping is None:
name_mapping = requested_schema.name_mapping

try:
provided_schema = pyarrow_to_schema(
Expand Down Expand Up @@ -3332,7 +3337,17 @@ def parquet_file_to_data_file(io: FileIO, table_metadata: TableMetadata, file_pa
arrow_schema = parquet_metadata.schema.to_arrow_schema()

schema = table_metadata.schema()
file_schema = _check_pyarrow_schema_compatible(schema, arrow_schema, format_version=table_metadata.format_version)
# Like the scan, use the table's name mapping, which keeps the old names of renamed columns.
file_schema = _check_pyarrow_schema_compatible(
schema, arrow_schema, format_version=table_metadata.format_version, name_mapping=table_metadata.name_mapping()
)
# Two columns can resolve to one field ID, for example the old and the new name of a renamed column.
names_by_id: dict[int, list[str]] = {}
for name, field_id in visit(file_schema, _IndexByName()).items():
names_by_id.setdefault(field_id, []).append(name)
for field_id, names in sorted(names_by_id.items()):
if len(names) > 1:
raise ValueError(f"Multiple file columns resolve to field ID {field_id}: {', '.join(sorted(names))}")

stats_columns = compute_statistics_plan(schema, table_metadata.properties)
parquet_column_mapping = _file_parquet_path_to_id_mapping(parquet_metadata, file_schema)
Expand Down
3 changes: 3 additions & 0 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1097,6 +1097,8 @@ def add_files(
FileNotFoundError: If the file does not exist.
ValueError: Raises a ValueError given file_paths contains duplicate files
ValueError: Raises a ValueError given file_paths already referenced by table
ValueError: Raises a ValueError given a file whose columns cannot be resolved unambiguously or are incompatible
with the table schema
ValidationException: Raises a ValidationException if a file becomes referenced during a commit retry
"""
if len(file_paths) != len(set(file_paths)):
Expand Down Expand Up @@ -1972,6 +1974,7 @@ def add_files(

Raises:
FileNotFoundError: If the file does not exist.
ValueError: If the columns of a file cannot be resolved unambiguously or are incompatible with the table schema.
"""
with self.transaction() as tx:
tx.add_files(
Expand Down
96 changes: 96 additions & 0 deletions tests/io/test_pyarrow.py
Original file line number Diff line number Diff line change
Expand Up @@ -3462,6 +3462,29 @@ def test_schema_downcast(table_schema_simple: Schema) -> None:
pytest.fail("Unexpected Exception raised when calling `_check_pyarrow_schema_compatible`")


def test_schema_compatible_with_name_mapping(table_schema_simple: Schema) -> None:
# The table renamed "foo" (field ID 1) to "qux", and the columns have no field IDs.
renamed_schema = Schema(NestedField(1, "qux", StringType(), required=False), *table_schema_simple.fields[1:])
other_schema = pa.schema(
(
pa.field("foo", pa.string(), nullable=True),
pa.field("bar", pa.int32(), nullable=False),
pa.field("baz", pa.bool_(), nullable=True),
)
)

file_schema = _check_pyarrow_schema_compatible(
renamed_schema, other_schema, name_mapping=create_mapping_from_schema(table_schema_simple)
)
assert file_schema.find_field("foo").field_id == 1

# Without a name mapping, the columns are matched by the names of the requested schema.
file_schema = _check_pyarrow_schema_compatible(renamed_schema, other_schema.set(0, pa.field("qux", pa.string())))
assert file_schema.find_field("qux").field_id == 1
with pytest.raises(ValueError, match="PyArrow table contains more columns: foo"):
_check_pyarrow_schema_compatible(renamed_schema, other_schema)


def test_add_files_matches_columns_by_field_id(catalog: InMemoryCatalog, tmp_path: str) -> None:
# Each file is valid for its table, but its column paths differ from the table's names.
nested_schema = Schema(
Expand Down Expand Up @@ -3547,6 +3570,79 @@ def test_add_files_matches_columns_by_field_id(catalog: InMemoryCatalog, tmp_pat
assert dict(table.inspect.files().to_pylist()[0]["value_counts"]) == value_counts


def test_add_files_matches_columns_by_table_name_mapping(catalog: InMemoryCatalog, tmp_path: str) -> None:
# The files have no field IDs. The first add_files stores the table's name mapping, and the renames
# keep the old names in it, so a file that still uses them is matched the way the scan reads it.
# The short names of the list of structs, like address.zip, must not count as a second column.
catalog.create_namespace("default")
identifier = "default.add_files_table_name_mapping"
catalog.create_table(
identifier,
schema=Schema(
NestedField(1, "id", LongType(), required=False),
NestedField(2, "name", StringType(), required=False),
NestedField(3, "address", ListType(4, StructType(NestedField(5, "zip", LongType())), element_required=False)),
),
)
file_schema = pa.schema([("id", pa.int64()), ("name", pa.string()), ("address", pa.list_(pa.struct([("zip", pa.int64())])))])
file_locs = []
for row_id, name, zip_code in [(1, "a", 98101), (2, "b", 10001), (3, "c", 94105)]:
file_loc = f"{tmp_path}/{row_id}.parquet"
pq.write_table(pa.table({"id": [row_id], "name": [name], "address": [[{"zip": zip_code}]]}, schema=file_schema), file_loc)
file_locs.append(file_loc)

catalog.load_table(identifier).add_files(file_locs[:1])
with catalog.load_table(identifier).update_schema() as update:
update.rename_column("name", "full_name")
update.rename_column("address.element.zip", "postal_code")
catalog.load_table(identifier).add_files(file_locs[1:2])

table = catalog.load_table(identifier)
assert sorted(table.scan().to_arrow().to_pylist(), key=lambda row: row["id"]) == [
{"id": 1, "full_name": "a", "address": [{"postal_code": 98101}]},
{"id": 2, "full_name": "b", "address": [{"postal_code": 10001}]},
]
assert [dict(file["value_counts"]) for file in table.inspect.files().to_pylist()] == [{1: 1, 2: 1, 5: 1}] * 2

# Both the old and the new name of a column in one file, in either order, resolve to one field ID, like a field ID
# that a file has twice. Such files are rejected.
old_name, new_name = pa.field("name", pa.string()), pa.field("full_name", pa.string())
both_zips = pa.field("address", pa.list_(pa.struct([("zip", pa.int64()), ("postal_code", pa.int64())])))
id_2 = {"PARQUET:field_id": "2"}
for i, (columns, error) in enumerate(
[
([old_name, new_name], "2: full_name, name"),
([new_name, old_name], "2: full_name, name"),
([both_zips], "5: address.element.postal_code, address.element.zip"),
([old_name.with_metadata(id_2), new_name.with_metadata(id_2)], "2: full_name, name"),
]
):
file_loc = f"{tmp_path}/duplicate_{i}.parquet"
pq.write_table(pa.Table.from_pylist([{}], schema=pa.schema(columns)), file_loc)
with pytest.raises(ValueError, match=f"Multiple file columns resolve to field ID {error}"):
catalog.load_table(identifier).add_files([file_loc])
assert catalog.load_table(identifier).current_snapshot() == table.current_snapshot()

# The mapping keeps the names of a dropped column too, but they no longer match a column of the table.
with table.update_schema() as update:
update.delete_column("full_name")
with pytest.raises(ValueError, match="PyArrow table contains more columns: name"):
catalog.load_table(identifier).add_files(file_locs[2:])

# A stored mapping that lacks a column of the table cannot resolve that column, so the file is rejected.
incomplete = catalog.create_table(
"default.add_files_incomplete_name_mapping",
schema=Schema(NestedField(1, "id", LongType(), required=False), NestedField(2, "name", StringType(), required=False)),
properties={TableProperties.DEFAULT_NAME_MAPPING: '[{"field-id": 1, "names": ["id"]}]'},
)
file_loc = f"{tmp_path}/incomplete.parquet"
pq.write_table(pa.table({"id": [1], "name": ["a"]}), file_loc)
metadata = incomplete.metadata
with pytest.raises(ValueError):
incomplete.add_files([file_loc])
assert catalog.load_table("default.add_files_incomplete_name_mapping").metadata == metadata


def test_add_files_with_field_ids_swapped_relative_to_names(catalog: InMemoryCatalog, tmp_path: str) -> None:
# The file's "a" is field ID 2 and its "b" is field ID 1, the reverse of the table, as after renames.
# Its bounds have to be recorded by field ID, or both filters below prune the file.
Expand Down