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
18 changes: 18 additions & 0 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -181,6 +181,12 @@ class TableProperties:
PARQUET_BLOOM_FILTER_MAX_BYTES_DEFAULT = 1024 * 1024

PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX = "write.parquet.bloom-filter-enabled.column"
PARQUET_BLOOM_FILTER_COLUMN_FPP_PREFIX = "write.parquet.bloom-filter-fpp.column"
PARQUET_BLOOM_FILTER_COLUMN_NDV_PREFIX = "write.parquet.bloom-filter-ndv.column"
PARQUET_COLUMN_STATS_ENABLED_PREFIX = "write.parquet.stats-enabled.column"
PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX = "write.parquet.compression-codec.column"
PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX = "write.parquet.compression-level.column"
PARQUET_DICT_ENCODING_ENABLED_COLUMN_PREFIX = "write.parquet.dict-encoding-enabled.column"

WRITE_TARGET_FILE_SIZE_BYTES = "write.target-file-size-bytes"
WRITE_TARGET_FILE_SIZE_BYTES_DEFAULT = 512 * 1024 * 1024 # 512 MB
Expand All @@ -193,6 +199,18 @@ class TableProperties:

METRICS_MODE_COLUMN_CONF_PREFIX = "write.metadata.metrics.column"

# Prefixes of the properties keyed by column name, renamed or removed when the column is renamed or dropped
COLUMN_PROPERTY_PREFIXES = (
METRICS_MODE_COLUMN_CONF_PREFIX,
PARQUET_BLOOM_FILTER_COLUMN_ENABLED_PREFIX,
PARQUET_BLOOM_FILTER_COLUMN_FPP_PREFIX,
PARQUET_BLOOM_FILTER_COLUMN_NDV_PREFIX,
PARQUET_COLUMN_STATS_ENABLED_PREFIX,
PARQUET_COLUMN_COMPRESSION_CODEC_PREFIX,
PARQUET_COLUMN_COMPRESSION_LEVEL_PREFIX,
PARQUET_DICT_ENCODING_ENABLED_COLUMN_PREFIX,
)

WRITE_PARTITION_SUMMARY_LIMIT = "write.summary.partition-limit"
WRITE_PARTITION_SUMMARY_LIMIT_DEFAULT = 0

Expand Down
35 changes: 35 additions & 0 deletions pyiceberg/table/update/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,7 @@
from pyiceberg.table.update import (
AddSchemaUpdate,
AssertCurrentSchemaId,
RemovePropertiesUpdate,
SetCurrentSchemaUpdate,
SetPropertiesUpdate,
TableRequirement,
Expand Down Expand Up @@ -664,6 +665,8 @@ def _commit(self) -> UpdatesAndRequirements:
SetPropertiesUpdate(updates={TableProperties.DEFAULT_NAME_MAPPING: updated_name_mapping.model_dump_json()}),
)

updates += _column_property_updates(self._transaction.table_metadata.properties, self._schema, new_schema)

return updates, requirements

def _apply(self) -> Schema:
Expand Down Expand Up @@ -712,6 +715,38 @@ def assign_new_column_id(self) -> int:
return next(self._last_column_id)


def _column_property_updates(properties: dict[str, str], old_schema: Schema, new_schema: Schema) -> tuple[TableUpdate, ...]:
"""Rename or remove the properties keyed by column name, so that they follow their columns to the new schema."""
from pyiceberg.table import TableProperties

renamed: dict[str, str] = {}
removals: list[str] = []
for key, value in properties.items():
prefix = next((prefix for prefix in TableProperties.COLUMN_PROPERTY_PREFIXES if key.startswith(f"{prefix}.")), None)
if prefix is None:
continue

field = old_schema._find_field_or_none(key[len(prefix) + 1 :], case_sensitive=True)
if field is None:
continue

old_name = old_schema.find_column_name(field.field_id)
new_name = new_schema.find_column_name(field.field_id)
if new_name != old_name:
removals.append(key)
if new_name is not None:
# The full-name key, which the writer applies, wins over a short name such as points.x for points.element.x
renamed[f"{prefix}.{new_name}"] = properties.get(f"{prefix}.{old_name}", value)

updates: tuple[TableUpdate, ...] = ()
if renamed:
updates += (SetPropertiesUpdate(updates=renamed),)
# Keep the keys that another renamed column takes over, e.g. when two columns swap names
if removals := [key for key in removals if key not in renamed]:
updates += (RemovePropertiesUpdate(removals=removals),)
return updates


class _ApplyChanges(SchemaVisitor[IcebergType | None]):
_adds: dict[int, builtins.list[NestedField]]
_updates: dict[int, NestedField]
Expand Down
91 changes: 91 additions & 0 deletions tests/table/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -953,6 +953,97 @@ def test_move_relative_to_nested_column_added_in_same_update(table_v2: Table) ->
update.move_before(("points", "z"), ("struct", "field1"))


def test_update_schema_moves_column_properties(catalog: Catalog) -> None:
import pyarrow as pa

catalog.create_namespace("default")
schema = Schema(
NestedField(1, "email", StringType(), required=False),
NestedField(2, "n", LongType(), required=False),
NestedField(3, "location", StructType(NestedField(4, "lat", DoubleType(), required=False)), required=False),
)
properties = {"write.metadata.metrics.column.email": "none", "write.metadata.metrics.column.location.lat": "none"}
table = catalog.create_table("default.column_properties", schema=schema, properties=properties)

with table.update_schema() as update:
update.rename_column("email", "contact_email")
update.rename_column("location", "loc")
assert table.properties == {
"write.metadata.metrics.column.contact_email": "none",
"write.metadata.metrics.column.loc.lat": "none",
}

# The metrics mode still applies to the renamed columns, so only n has a value count
table.append(pa.table({"contact_email": ["bob@example.com"], "n": pa.array([1], pa.int64()), "loc": [{"lat": 1.0}]}))
assert [task.file.value_counts for task in table.scan().plan_files()] == [{2: 1}]

# Dropping a column removes its properties, also when a new column takes its name
with table.update_schema() as update:
update.delete_column("contact_email")
update.add_column("contact_email", StringType())
update.delete_column("loc")
assert catalog.load_table("default.column_properties").properties == {}


def test_update_schema_column_properties_in_transaction(catalog: Catalog) -> None:
catalog.create_namespace("default")
schema = Schema(*(NestedField(field_id, name, LongType(), required=False) for field_id, name in enumerate("abc", start=1)))
table = catalog.create_table("default.column_properties", schema=schema)
prefixes = [
"write.metadata.metrics.column",
"write.parquet.bloom-filter-enabled.column",
"write.parquet.bloom-filter-fpp.column",
"write.parquet.bloom-filter-ndv.column",
"write.parquet.stats-enabled.column",
"write.parquet.compression-codec.column",
"write.parquet.compression-level.column",
"write.parquet.dict-encoding-enabled.column",
]

with table.transaction() as txn:
txn.set_properties({f"{prefix}.{name}": name for prefix in prefixes for name in ["a", "b", "B", "c", "missing"]})
with txn.update_schema() as update:
update.delete_column("a")
update.rename_column("b", "a")
update.rename_column("c", "missing")

# The properties of b and c move to their new names, the ones of the dropped a are removed, and B matches no column
assert catalog.load_table("default.column_properties").properties == {
f"{prefix}.{name}": value for prefix in prefixes for name, value in [("a", "b"), ("B", "B"), ("missing", "c")]
}


def test_update_schema_prefers_full_name_column_property(catalog: Catalog) -> None:
import pyarrow as pa

catalog.create_namespace("default")
lat = NestedField(3, "lat", LongType(), required=False)
schema = Schema(NestedField(1, "points", ListType(2, StructType(lat), element_required=False), required=False))
full_name = {"write.metadata.metrics.column.points.element.lat": "none"}
short_name = {"write.metadata.metrics.column.points.lat": "full"}

orders = {"default.full_first": {**full_name, **short_name}, "default.short_first": {**short_name, **full_name}}
for identifier, column_properties in orders.items():
properties = {"write.metadata.metrics.default": "none", **column_properties}
table = catalog.create_table(identifier, schema=schema, properties=properties)
with table.update_schema() as update:
update.rename_column("points", "pts")
assert table.properties == {
"write.metadata.metrics.default": "none",
"write.metadata.metrics.column.pts.element.lat": "none",
}

# The writer applies the full-name key, so lat still has no metrics
table.append(pa.table({"pts": [[{"lat": 1}]]}))
assert [task.file.value_counts for task in table.scan().plan_files()] == [{}]

# A short-name key alone moves to the full name, as in Java
table = catalog.create_table("default.short_only", schema=schema, properties=short_name)
with table.update_schema() as update:
update.rename_column("points", "pts")
assert table.properties == {"write.metadata.metrics.column.pts.element.lat": "full"}


def test_update_column(table_v1: Table, table_v2: Table) -> None:
"""
Table should be able to update existing property `doc`
Expand Down
Loading