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
11 changes: 11 additions & 0 deletions mkdocs/docs/api.md
Original file line number Diff line number Diff line change
Expand Up @@ -185,6 +185,17 @@ with catalog.create_table_transaction(identifier="docs_example.bids", schema=sch
txn.set_properties(test_a="test_aa", test_b="test_b", test_c="test_c")
```

## Create or replace a table

`create_or_replace_table_transaction` creates the table, or atomically replaces it when it already exists (`CREATE OR REPLACE TABLE ... AS SELECT`). The new schema, partition spec, sort order and data become visible in a single commit, so readers never see an empty or half-written table:

```python
with catalog.create_or_replace_table_transaction(identifier="docs_example.bids", schema=df.schema) as txn:
txn.append(df)
```

A replaced table keeps its UUID and snapshot history, field IDs are reused for columns with the same name, and the given properties are merged into the existing ones. Use `replace_table_transaction` to fail with `NoSuchTableError` when the table does not exist.

## Register a table

To register a table using existing metadata:
Expand Down
62 changes: 62 additions & 0 deletions pyiceberg/catalog/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,6 +49,7 @@
DOWNCAST_NS_TIMESTAMP_TO_US_ON_WRITE,
CommitTableResponse,
CreateTableTransaction,
ReplaceTableTransaction,
StagedTable,
Table,
TableProperties,
Expand Down Expand Up @@ -493,6 +494,67 @@ def create_table_if_not_exists(
except TableAlreadyExistsError:
return self.load_table(identifier)

def replace_table_transaction(
self,
identifier: str | Identifier,
schema: Schema | pa.Schema,
location: str | None = None,
partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
sort_order: SortOrder = UNSORTED_SORT_ORDER,
properties: Properties = EMPTY_DICT,
) -> ReplaceTableTransaction:
"""Create a ReplaceTableTransaction that atomically replaces an existing table.

The table keeps its UUID and history, but the main branch is removed until new data is
written in the transaction. Field IDs are reused by name, and the given properties are
merged into the existing ones.

Args:
identifier (str | Identifier): Table identifier.
schema (Schema): Table's new schema.
location (str | None): New location for the table. Defaults to the current location.
partition_spec (PartitionSpec): New PartitionSpec for the table.
sort_order (SortOrder): New SortOrder for the table.
properties (Properties): Table properties to set on the table.

Returns:
ReplaceTableTransaction: the transaction to stage changes in and commit.

Raises:
NoSuchTableError: If a table with the name does not exist.
"""
table = self.load_table(identifier)
format_version = int(properties.get(TableProperties.FORMAT_VERSION, table.metadata.format_version))
iceberg_schema = self._convert_schema_if_needed(schema, format_version) # type: ignore
return ReplaceTableTransaction(table, iceberg_schema, location, partition_spec, sort_order, properties)

def create_or_replace_table_transaction(
self,
identifier: str | Identifier,
schema: Schema | pa.Schema,
location: str | None = None,
partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
sort_order: SortOrder = UNSORTED_SORT_ORDER,
properties: Properties = EMPTY_DICT,
) -> CreateTableTransaction | ReplaceTableTransaction:
"""Create a transaction that creates the table, or atomically replaces it if it already exists.

Args:
identifier (str | Identifier): Table identifier.
schema (Schema): Table's schema.
location (str | None): Location for the table. Optional Argument.
partition_spec (PartitionSpec): PartitionSpec for the table.
sort_order (SortOrder): SortOrder for the table.
properties (Properties): Table properties that can be a string based dictionary.

Returns:
CreateTableTransaction | ReplaceTableTransaction: the transaction to stage changes in and commit.
"""
try:
return self.replace_table_transaction(identifier, schema, location, partition_spec, sort_order, properties)
except NoSuchTableError:
return self.create_table_transaction(identifier, schema, location, partition_spec, sort_order, properties)

@abstractmethod
def load_table(self, identifier: str | Identifier) -> Table:
"""Load the table's metadata and returns the table instance.
Expand Down
23 changes: 23 additions & 0 deletions pyiceberg/schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -1342,6 +1342,13 @@ def assign_fresh_schema_ids(schema_or_type: Schema | IcebergType, next_id: Calla
return pre_order_visit(schema_or_type, _SetFreshIDs(next_id_func=next_id))


def assign_fresh_schema_ids_for_replace(schema: Schema, base_schema: Schema, last_column_id: int) -> Schema:
"""Assign fresh IDs, reusing the base schema's ID for fields with the same name, like Java's TypeUtil.assignFreshIds."""
# Make the IDs unique first: schemas converted from PyArrow have -1 for every field
schema = assign_fresh_schema_ids(schema)
return pre_order_visit(schema, _SetFreshIDsReusingBase(schema, base_schema, last_column_id))


class _SetFreshIDs(PreOrderSchemaVisitor[IcebergType]):
"""Traverses the schema and assigns monotonically increasing ids."""

Expand Down Expand Up @@ -1404,6 +1411,22 @@ def primitive(self, primitive: PrimitiveType) -> PrimitiveType:
return primitive


class _SetFreshIDsReusingBase(_SetFreshIDs):
"""Reuses the base schema's ID for fields with the same name and assigns new IDs above last_column_id otherwise."""

def __init__(self, schema: Schema, base_schema: Schema, last_column_id: int) -> None:
counter = itertools.count(last_column_id + 1)
super().__init__(lambda: next(counter))
self._names = index_name_by_id(schema)
self._base_ids = index_by_name(base_schema)

def _get_and_increment(self, current_id: int) -> int:
name = self._names[current_id]
new_id = self._base_ids[name] if name in self._base_ids else self.next_id_func()
self.old_id_to_new_id[current_id] = new_id
return new_id


# Implementation copied from Apache Iceberg repo.
def make_compatible_name(name: str) -> str:
"""Make a field name compatible with Avro specification.
Expand Down
170 changes: 166 additions & 4 deletions pyiceberg/table/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -56,14 +56,26 @@
ManifestEntryStatus,
ManifestFile,
)
from pyiceberg.partitioning import PARTITION_FIELD_ID_START, UNPARTITIONED_PARTITION_SPEC, PartitionKey, PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.partitioning import (
PARTITION_FIELD_ID_START,
UNPARTITIONED_PARTITION_SPEC,
PartitionField,
PartitionKey,
PartitionSpec,
assign_fresh_partition_spec_ids,
)
from pyiceberg.schema import Schema, assign_fresh_schema_ids_for_replace
from pyiceberg.table.delete_file_index import DeleteFileIndex
from pyiceberg.table.inspect import InspectTable
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,
_check_properties_format_version_compatibility,
)
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 All @@ -75,17 +87,23 @@
is_ancestor_of,
is_parent_ancestor_of,
)
from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder
from pyiceberg.table.sorting import UNSORTED_SORT_ORDER, SortOrder, assign_fresh_sort_order_ids
from pyiceberg.table.update import (
AddPartitionSpecUpdate,
AddSchemaUpdate,
AddSnapshotUpdate,
AddSortOrderUpdate,
AssertCreate,
AssertCurrentSchemaId,
AssertDefaultSortOrderId,
AssertDefaultSpecId,
AssertLastAssignedFieldId,
AssertLastAssignedPartitionId,
AssertRefSnapshotId,
AssertTableUUID,
AssignUUIDUpdate,
RemovePropertiesUpdate,
RemoveSnapshotRefUpdate,
SetCurrentSchemaUpdate,
SetDefaultSortOrderUpdate,
SetDefaultSpecUpdate,
Expand Down Expand Up @@ -1361,6 +1379,150 @@ def commit_transaction(self) -> Table:
return self._table


class ReplaceTableTransaction(Transaction):
"""A transaction that atomically replaces the definition and data of an existing table.

Mirrors Java's TableMetadata.buildReplacement: the UUID, snapshots and history are kept, the main
branch is removed, field IDs are reused by name, and properties are merged into the existing ones.
"""

def __init__(
self,
table: Table,
schema: Schema,
location: str | None = None,
partition_spec: PartitionSpec = UNPARTITIONED_PARTITION_SPEC,
sort_order: SortOrder = UNSORTED_SORT_ORDER,
properties: Properties = EMPTY_DICT,
):
super().__init__(table, autocommit=False)
base = table.metadata
properties = dict(properties)
format_version = int(properties.pop(TableProperties.FORMAT_VERSION, base.format_version))
Comment thread
malon64 marked this conversation as resolved.
Resolved
if format_version < base.format_version:
raise ValueError(f"Cannot downgrade v{base.format_version} table to v{format_version}")
if format_version > base.format_version and format_version > SUPPORTED_TABLE_FORMAT_VERSION:
raise ValueError(f"Unsupported table format version: {format_version}")
if format_version == 1 and not (base.spec().is_unpartitioned() and partition_spec.is_unpartitioned()):
# TODO: support Java's carry-forward of the current v1 partition fields as void transforms
raise ValueError("Replacing a partitioned v1 table is not supported, set format-version to 2 or higher")
schema.check_format_version_compatibility(format_version)
_check_properties_format_version_compatibility(properties, format_version)

fresh_schema = assign_fresh_schema_ids_for_replace(schema, base.schema(), base.last_column_id)
fresh_spec = assign_fresh_partition_spec_ids(partition_spec, schema, fresh_schema)
fresh_sort_order = assign_fresh_sort_order_ids(sort_order, schema, fresh_schema)

if format_version > base.format_version:
self._updates += (UpgradeFormatVersionUpdate(format_version=format_version),)
if MAIN_BRANCH in base.refs:
self._updates += (RemoveSnapshotRefUpdate(ref_name=MAIN_BRANCH),)

# Reuse partition field IDs by (source, transform) across all specs, new fields get IDs above last_partition_id
existing_fields = sorted((f for s in base.partition_specs for f in s.fields), key=lambda f: f.field_id)
field_ids = {(f.source_id, str(f.transform)): f.field_id for f in existing_fields} # highest ID wins, like Java
next_field_id = itertools.count((base.last_partition_id or PARTITION_FIELD_ID_START - 1) + 1)
fresh_spec = PartitionSpec(
*[
PartitionField(
source_id=f.source_id,
field_id=field_ids.get((f.source_id, str(f.transform))) or next(next_field_id),
transform=f.transform,
name=f.name,
)
for f in fresh_spec.fields
]
)

# Reuse an existing schema, spec or sort order when identical, otherwise add it and make it the default
if (schema_id := next((s.schema_id for s in base.schemas if s == fresh_schema), None)) is not None:
self._updates += (SetCurrentSchemaUpdate(schema_id=schema_id),)
else:
new_schema_id = max(s.schema_id for s in base.schemas) + 1
self._updates += (
AddSchemaUpdate(schema_=fresh_schema.model_copy(update={"schema_id": new_schema_id})),
SetCurrentSchemaUpdate(schema_id=-1),
)

if (spec_id := next((s.spec_id for s in base.partition_specs if s.fields == fresh_spec.fields), None)) is not None:
self._updates += (SetDefaultSpecUpdate(spec_id=spec_id),)
else:
new_spec_id = max(s.spec_id for s in base.partition_specs) + 1
self._updates += (
AddPartitionSpecUpdate(spec=PartitionSpec(*fresh_spec.fields, spec_id=new_spec_id)),
SetDefaultSpecUpdate(spec_id=-1),
)

if (order_id := next((o.order_id for o in base.sort_orders if o.fields == fresh_sort_order.fields), None)) is not None:
self._updates += (SetDefaultSortOrderUpdate(sort_order_id=order_id),)
elif fresh_sort_order.is_unsorted:
# The unsorted order always has ID 0
self._updates += (AddSortOrderUpdate(sort_order=UNSORTED_SORT_ORDER), SetDefaultSortOrderUpdate(sort_order_id=0))
else:
new_order_id = max(o.order_id for o in base.sort_orders) + 1
self._updates += (
AddSortOrderUpdate(sort_order=SortOrder(*fresh_sort_order.fields, order_id=new_order_id)),
SetDefaultSortOrderUpdate(sort_order_id=-1),
)

if location and location.rstrip("/") != base.location:
Comment thread
malon64 marked this conversation as resolved.
Resolved
self._updates += (SetLocationUpdate(location=location.rstrip("/")),)
if properties:
self._updates += (SetPropertiesUpdate(updates=properties),)

def commit_transaction(self) -> Table:
"""Commit the replacement to the catalog.

Like Java's UpdateRequirements.forReplaceTable, the main branch and current IDs are overwritten
regardless of concurrent changes; only the table identity and ID assignment are asserted.

Unlike Java, the current schema, spec or sort order is also asserted when a new one is added: the
catalogs in PyIceberg keep the IDs assigned by the client, so a concurrent addition would reuse the ID.
When data is written, main is also asserted: the new snapshot has no parent, so a concurrent commit
would otherwise make the table's last sequence number go backwards.

Returns:
The table with the updates applied.
"""
if self._failed:
raise RuntimeError("This transaction failed to commit and cannot be reused; create a new transaction.")
if len(self._updates) > 0:
base = self._table.metadata
requirements: tuple[TableRequirement, ...] = (
AssertTableUUID(uuid=base.table_uuid),
AssertLastAssignedFieldId(last_assigned_field_id=base.last_column_id),
AssertLastAssignedPartitionId(last_assigned_partition_id=base.last_partition_id),
)
update_types = {type(update) for update in self._updates}
if AddSchemaUpdate in update_types:
requirements += (AssertCurrentSchemaId(current_schema_id=base.current_schema_id),)
if AddPartitionSpecUpdate in update_types:
requirements += (AssertDefaultSpecId(default_spec_id=base.default_spec_id),)
if AddSortOrderUpdate in update_types:
requirements += (AssertDefaultSortOrderId(default_sort_order_id=base.default_sort_order_id),)
if self._snapshot_producers:
requirements += (AssertRefSnapshotId(ref=MAIN_BRANCH, snapshot_id=base.current_snapshot_id),)
try:
try:
self._table._do_commit(updates=self._updates, requirements=requirements) # pylint: disable=W0212
except CommitFailedException:
# Same as Transaction.commit_transaction: only delete the written files when the commit did not land
if not (self._snapshot_producers and self._attempt_landed()):
for producer in self._snapshot_producers:
producer._clean_all_uncommitted()
raise
except Exception:
self._failed = True
raise

self._snapshot_producers = []

self._updates = ()
self._requirements = ()

return self._table


class Namespace(IcebergRootModel[list[str]]):
"""Reference to one or more levels of a namespace."""

Expand Down
9 changes: 7 additions & 2 deletions pyiceberg/table/update/snapshot.py
Original file line number Diff line number Diff line change
Expand Up @@ -57,6 +57,7 @@
)
from pyiceberg.partitioning import PartitionSpec
from pyiceberg.schema import Schema
from pyiceberg.table.locations import load_location_provider
from pyiceberg.table.refs import MAIN_BRANCH, SnapshotRef, SnapshotRefType
from pyiceberg.table.snapshots import (
Operation,
Expand Down Expand Up @@ -344,7 +345,9 @@ def _commit(self) -> UpdatesAndRequirements:
attempt=0,
commit_uuid=self.commit_uuid,
)
location_provider = self._transaction._table.location_provider()
location_provider = load_location_provider(
self._transaction.table_metadata.location, self._transaction.table_metadata.properties
)
manifest_list_file_path = location_provider.new_metadata_location(file_name)
self._written_manifest_lists.append(manifest_list_file_path)

Expand Down Expand Up @@ -422,7 +425,9 @@ def new_manifest_writer(self, spec: PartitionSpec) -> ManifestWriter:
)

def new_manifest_output(self) -> OutputFile:
location_provider = self._transaction._table.location_provider()
location_provider = load_location_provider(
self._transaction.table_metadata.location, self._transaction.table_metadata.properties
)
file_name = _new_manifest_file_name(num=next(self._manifest_num_counter), commit_uuid=self.commit_uuid)
file_path = location_provider.new_metadata_location(file_name)
self._written_manifests.append(file_path)
Expand Down
Loading