Skip to content
Draft
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: 14 additions & 5 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
from functools import cached_property
from itertools import chain
from types import TracebackType
from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar
from typing import TYPE_CHECKING, Any, NamedTuple, TypeVar, cast

from cachetools import LRUCache
from pydantic import Field
Expand Down Expand Up @@ -63,7 +63,7 @@
from pyiceberg.table.labels import Labels
from pyiceberg.table.locations import LocationProvider, load_location_provider
from pyiceberg.table.maintenance import MaintenanceTable
from pyiceberg.table.metadata import INITIAL_SEQUENCE_NUMBER, TableMetadata
from pyiceberg.table.metadata import INITIAL_SEQUENCE_NUMBER, SUPPORTED_TABLE_FORMAT_VERSION, TableMetadata
from pyiceberg.table.metadata_columns import project_schema, split_selected_fields
from pyiceberg.table.name_mapping import NameMapping
from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef
Expand Down Expand Up @@ -353,7 +353,7 @@ def upgrade_table_version(self, format_version: TableVersion) -> Transaction:
Returns:
The alter table builder.
"""
if format_version not in {1, 2}:
if not 1 <= format_version <= SUPPORTED_TABLE_FORMAT_VERSION:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Before we open this up, should we make sure we can actually write to a v3 table? With #3551 applied locally, upgrade_table_version(3) followed by tbl.append(df) raises ValueError: Cannot write manifest for table version: 3. Users would be able to upgrade a table that PyIceberg then can't append to. I think we should at least document this, or gate it until v3 manifest writes (#3624) land. @kevinjqliu @rambleraptor WDYT?

raise ValueError(f"Unsupported table format version: {format_version}")

if format_version < self.table_metadata.format_version:
Expand All @@ -369,6 +369,9 @@ def set_properties(self, properties: Properties = EMPTY_DICT, **kwargs: Any) ->

When a property is already set, it will be overwritten.

Setting the `format-version` property upgrades the table to that format
version instead of storing it as a property.

Args:
properties: The properties set on the table.
kwargs: properties can also be pass as kwargs.
Expand All @@ -378,8 +381,14 @@ def set_properties(self, properties: Properties = EMPTY_DICT, **kwargs: Any) ->
"""
if properties and kwargs:
raise ValueError("Cannot pass both properties and kwargs")
updates = properties or kwargs
return self._apply((SetPropertiesUpdate(updates=updates),))
updates = dict(properties or kwargs)
if (new_format_version := updates.pop(TableProperties.FORMAT_VERSION, None)) is not None:
if isinstance(new_format_version, bool) or not str(new_format_version).isdigit():
raise ValueError(f"Invalid format-version: {new_format_version}")
self.upgrade_table_version(format_version=cast(TableVersion, int(new_format_version)))
if updates:
return self._apply((SetPropertiesUpdate(updates=updates),))
return self
Comment on lines +384 to +391

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This matches Java's replaceProperties, but it's a separate concern, it isn't mentioned in the description, and it changes set_properties behavior for v1/v2 tables too. Could we split it into its own PR? Then this one stays minimal. If we keep it, we could reuse property_as_int from pyiceberg.utils.properties instead of the bool/isdigit handling, and let upgrade_table_version reject unsupported versions.


def _set_ref_snapshot(
self,
Expand Down
5 changes: 4 additions & 1 deletion pyiceberg/table/metadata.py
Original file line number Diff line number Diff line change
Expand Up @@ -71,7 +71,10 @@
INITIAL_ROW_ID = 0
DEFAULT_SCHEMA_ID = 0

SUPPORTED_TABLE_FORMAT_VERSION = 2
SUPPORTED_TABLE_FORMAT_VERSION = 3

INITIAL_ROW_ID = 0
"""The initial value of `next-row-id` for newly upgraded V3 tables."""
Comment on lines +75 to +77

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

INITIAL_ROW_ID = 0 is already defined a few lines up, and update/__init__.py already imports it from there. Can we drop the redefinition?

Suggested change
INITIAL_ROW_ID = 0
"""The initial value of `next-row-id` for newly upgraded V3 tables."""



def cleanup_snapshot_id(data: dict[str, Any]) -> dict[str, Any]:
Expand Down
5 changes: 4 additions & 1 deletion pyiceberg/table/update/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -340,7 +340,10 @@ def _(
elif update.format_version == base_metadata.format_version:
return base_metadata

updated_metadata = base_metadata.model_copy(update={"format_version": update.format_version})
updates: dict[str, Any] = {"format_version": update.format_version}
if update.format_version >= 3 and getattr(base_metadata, "next_row_id", None) is None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We only get here when upgrading, and the highest supported version is 3, so base_metadata is always V1/V2 and doesn't have next_row_id. I think the getattr can go, mirroring Java where nextRowId stays at INITIAL_ROW_ID until v3:

Suggested change
if update.format_version >= 3 and getattr(base_metadata, "next_row_id", None) is None:
if update.format_version >= 3:

updates["next_row_id"] = INITIAL_ROW_ID
updated_metadata = base_metadata.model_copy(update=updates)

context.add_update(update)
return TableMetadataUtil._construct_without_validation(updated_metadata)
Expand Down
18 changes: 15 additions & 3 deletions tests/integration/test_reads.py
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,7 @@
import uuid
from datetime import datetime, timedelta
from pathlib import PosixPath
from typing import Any
from typing import Any, cast
from urllib.parse import urlparse

import pyarrow as pa
Expand Down Expand Up @@ -55,6 +55,7 @@
from pyiceberg.schema import Schema
from pyiceberg.table import Table
from pyiceberg.table.snapshots import Operation
from pyiceberg.typedef import TableVersion
from pyiceberg.types import (
BinaryType,
BooleanType,
Expand Down Expand Up @@ -979,10 +980,21 @@ def test_upgrade_table_version(catalog: Catalog) -> None:
transaction.upgrade_table_version(format_version=1)
assert "Cannot downgrade v2 table to v1" in str(e.value)

with table_test_table_version.transaction() as transaction:
transaction.upgrade_table_version(format_version=3)

assert table_test_table_version.format_version == 3
assert table_test_table_version.metadata.next_row_id == 0

# the upgraded metadata must persist and reload from the catalog
reloaded = catalog.load_table("default.test_table_version")
assert reloaded.format_version == 3
assert reloaded.metadata.next_row_id == 0

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

default.test_table_version is empty, so this doesn't show that existing data is still readable after the upgrade. How about also creating a v2 table with some rows, upgrading it to v3, and then asserting that both PyIceberg and Spark read the same rows? The Spark read checks that Java accepts the metadata we wrote.


with pytest.raises(ValueError) as e:
with table_test_table_version.transaction() as transaction:
transaction.upgrade_table_version(format_version=3)
assert "Unsupported table format version: 3" in str(e.value)
transaction.upgrade_table_version(format_version=cast(TableVersion, 4))
assert "Unsupported table format version: 4" in str(e.value)


@pytest.mark.integration
Expand Down
62 changes: 62 additions & 0 deletions tests/table/test_init.py
Original file line number Diff line number Diff line change
Expand Up @@ -93,6 +93,7 @@
SetSnapshotRefUpdate,
SetStatisticsUpdate,
TableUpdate,
UpgradeFormatVersionUpdate,
_apply_table_update,
_TableMetadataUpdateContext,
update_table_metadata,
Expand Down Expand Up @@ -1462,6 +1463,60 @@ def test_update_metadata_with_multiple_updates(table_v1: Table) -> None:
assert new_metadata.properties == {"owner": "test", "test_a": "test_a1"}


def test_update_metadata_upgrade_to_v3(table_v2: Table) -> None:
from pyiceberg.table.metadata import TableMetadataV3

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Nit: TableMetadataV3 can be imported at the top of the file, next to TableMetadataV2, instead of inside the test. Same for the next test.


new_metadata = update_table_metadata(table_v2.metadata, (UpgradeFormatVersionUpdate(format_version=3),))
assert isinstance(new_metadata, TableMetadataV3)
assert new_metadata.format_version == 3
assert new_metadata.next_row_id == 0

# rebuild the metadata to trigger validation
validated = TableMetadataUtil.parse_obj(copy(new_metadata.model_dump()))
assert validated.format_version == 3
assert validated.next_row_id == 0


def test_update_metadata_upgrade_v1_to_v3(table_v1: Table) -> None:
from pyiceberg.table.metadata import TableMetadataV3

new_metadata = update_table_metadata(table_v1.metadata, (UpgradeFormatVersionUpdate(format_version=3),))
assert isinstance(new_metadata, TableMetadataV3)
assert new_metadata.format_version == 3
assert new_metadata.next_row_id == 0

# rebuild the metadata to trigger validation
validated = TableMetadataUtil.parse_obj(copy(new_metadata.model_dump()))
assert validated.format_version == 3
assert validated.next_row_id == 0


def test_update_metadata_upgrade_same_version_is_noop(table_v2: Table) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This already passes on main, so it doesn't test the change here. Can we remove it? Less is more 👍

new_metadata = update_table_metadata(table_v2.metadata, (UpgradeFormatVersionUpdate(format_version=2),))
assert new_metadata == table_v2.metadata
assert new_metadata.format_version == 2


def test_set_properties_format_version_upgrades(table_v2: Table) -> None:
transaction = table_v2.transaction()
transaction.set_properties({"format-version": "3", "owner": "test"})

assert transaction.table_metadata.format_version == 3
assert transaction.table_metadata.next_row_id == 0
assert transaction.table_metadata.properties["owner"] == "test"
assert "format-version" not in transaction.table_metadata.properties
assert UpgradeFormatVersionUpdate(format_version=3) in transaction._updates


def test_set_properties_same_format_version_is_noop(table_v2: Table) -> None:
transaction = table_v2.transaction()
transaction.set_properties({"format-version": "2"})

assert transaction.table_metadata.format_version == 2
assert "format-version" not in transaction.table_metadata.properties
assert transaction._updates == ()


def test_update_metadata_schema_immutability(
table_v2_with_fixed_and_decimal_types: TableMetadataV2,
) -> None:
Expand Down Expand Up @@ -2659,3 +2714,10 @@ def mock_scan_iceberg(source: Any, **kwargs: Any) -> Any:
table_v2,
{"storage_options": storage_options, "snapshot_id": 12345, "reader_override": "native"},
)


def test_set_properties_invalid_format_version_rejected(table_v2: Table) -> None:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Could we move this next to the other set_properties tests? Appending it at the end of the file is what's causing the merge conflict with main.

transaction = table_v2.transaction()
for invalid in ("3.0", "three", "-1"):
with pytest.raises(ValueError, match="Invalid format-version"):
transaction.set_properties({"format-version": invalid})
Loading