Skip to content

Add atomic create or replace table - #4496

Open
malon64 wants to merge 3 commits into
apache:mainfrom
malon64:feat/create-or-replace-table
Open

malon64 wants to merge 3 commits into
apache:mainfrom
malon64:feat/create-or-replace-table

Conversation

@malon64

@malon64 malon64 commented Nov 25, 2026 •

Copy link
Copy Markdown

Closes #4485

Rationale for this change

Engines built on PyIceberg (e.g. Polars with its Iceberg SQL support, used from dbt) need CREATE OR REPLACE TABLE ... AS SELECT that swaps the definition and data in a single commit, so a failed transformation never leaves readers with an empty or half-written table. Java has this through createOrReplaceTransaction(); PyIceberg had no equivalent.

This adds three methods to Catalog:

with catalog.create_or_replace_table_transaction("db.orders", schema=df.schema) as txn:
    txn.append(df)
  • replace_table_transaction: replaces an existing table, raises NoSuchTableError otherwise
  • create_or_replace_table_transaction: replaces the table if it exists, otherwise creates it
  • create_or_replace_table: the same without staging data

The new ReplaceTableTransaction follows Java's TableMetadata.buildReplacement:

  • Keeps the table UUID and snapshot history and removes main, so the new snapshot starts a fresh lineage
  • Reuses field IDs by name (TypeUtil.assignFreshIds with a base schema), including nested fields and PyArrow schemas
  • Reuses partition field IDs by (source_id, transform) across all specs, highest ID wins (reassignPartitionIds)
  • Reuses an identical existing schema, spec or sort order rather than adding a duplicate
  • Merges properties into the existing ones; format-version can upgrade the table
  • On commit, asserts only the table UUID and the last assigned field and partition IDs, like UpdateRequirements.forReplaceTable; current IDs and refs are overwritten. The commit is not retried, since the replacement was built against the loaded metadata

The methods are concrete on the base Catalog and only use load_table and commit_table, so they work for every catalog, REST included (this matches how Java's REST client builds the replacement client side).

This is a smaller take on the approach in the earlier #3220, which was closed for inactivity.

Notes for reviewers

  • Deviation from Java: partitioned v1 tables are rejected with a clear error instead of carrying forward the current partition fields as void transforms. Upgrading through format-version=2 in the same replace avoids it. Happy to add the v1 carry-forward here or in a follow-up.
  • Deviation from Java: the last-assigned field and partition IDs are always asserted, not only when a schema or spec is added. This is stricter and can only cause extra conflicts, never wrong metadata.
  • Deviation from Java: when the replace adds a new schema, partition spec or sort order, the current one is also asserted. Java does not need this because the REST server reassigns those IDs on add, but PyIceberg's own catalogs (SQL, Glue, Hive, DynamoDB) keep the IDs assigned by the client. Without it, a concurrent change that adds no column IDs (e.g. a rename) would reuse the schema ID, leaving duplicate schema IDs and silently dropping the replacement schema.
  • When the table does not exist, the create path reuses create_table_transaction, so it inherits that method's existing lack of hierarchical namespace support in the SQL and memory catalogs.

Are these changes tested?

Yes:

  • tests/catalog/test_catalog_behaviors.py: create then replace with data (UUID, field ID reuse, merged properties, kept history, only new data visible), partition spec and schema reuse, NoSuchTableError for a missing table, and a commit failure when the table was dropped and recreated, or when a concurrent schema or sort-order change happened.
  • tests/test_schema.py: field ID reuse by name for nested fields and -1 IDs.

make lint passes. The catalog, table and schema suites pass locally, except 4 Hive Kerberos tests that need the hive-kerberos extra, which was not installed. REST and Spark integration tests were not run locally.

Are there any user-facing changes?

Yes: three new public Catalog methods and a "Create or replace a table" section in mkdocs/docs/api.md.

Add replace_table_transaction, create_or_replace_table_transaction and
create_or_replace_table to Catalog, so engines like Polars can run
CREATE OR REPLACE TABLE AS SELECT (e.g. for dbt) in a single commit.

Mirrors Java's TableMetadata.buildReplacement: the table keeps its UUID
and history, main is removed, field ids are reused by name, partition
field ids by (source, transform), and properties are merged. The commit
asserts only the table UUID and last assigned ids, like
UpdateRequirements.forReplaceTable.

Closes apache#4485
@malon64
malon64 force-pushed the feat/create-or-replace-table branch from 7beaacf to f1d881c Compare November 25, 2026 23:06
@korsakowii

Copy link
Copy Markdown

I have some additional validation results for f1d881c using SQLite and the Apache REST fixture with local storage.

  • Aborting after writing and reading back two new Parquet files left the original table unchanged.
  • A rejected metadata pointer update in SQLite and an HTTP 409 following a concurrent schema change in REST preserved the last committed state.
  • Successful replacement published the new data while preserving the table UUID and access to historical snapshots.

All six checks passed across both catalogs.

Comment thread pyiceberg/catalog/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
Comment thread pyiceberg/table/__init__.py Resolved
Drop create_or_replace_table, the transaction already covers it.
Clean up written files and refuse reuse when a replace commit fails,
like Transaction.commit_transaction. Build the snapshot producer's
location provider from the transaction metadata, so a new location or
write.metadata.path applies to manifests too. Validate the target
format version and properties up front.
The replaced main has no parent, so a snapshot built from a stale base
is accepted with an old sequence number and a concurrent commit makes
last-sequence-number go backwards. Fail the replace instead.

Also run the new replace tests with a single identifier fixture.

This branch has not been deployed

No deployments
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Feature: Revive atomic REPLACE TABLE support in PyIceberg

3 participants