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
51 changes: 45 additions & 6 deletions pyiceberg/table/upsert_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -72,13 +72,50 @@ def _values_differ(
return pc.invert(pc.or_(equal, both_null))


def _common_type(source_type: pa.DataType, target_type: pa.DataType) -> pa.DataType:
"""Return a type that can hold values from both columns without losing precision."""
if source_type == target_type:
return source_type
unified = pa.unify_schemas(
[pa.schema([pa.field("value", source_type)]), pa.schema([pa.field("value", target_type)])],
promote_options="permissive",
)
return unified.field("value").type


def _align_to_schema(table: pa.Table, schema: pa.Schema) -> pa.Table:
"""Align a table to a schema by column name, adding missing columns as nulls.

Columns present in both are promoted to a common type so that values are compared at full
precision, rather than narrowing a wider stored column to the type of the incoming data.
"""
fields = []
columns = []
for field in schema:
column = table.column(field.name) if field.name in table.column_names else None
if column is not None:
common_type = _common_type(column.type, field.type)
if column.type != common_type:
column = column.cast(common_type)
field = field.with_type(common_type)
else:
column = pa.nulls(len(table), type=field.type)
fields.append(field)
columns.append(column)
return pa.Table.from_arrays(columns, schema=pa.schema(fields))


def get_rows_to_update(source_table: pa.Table, target_table: pa.Table, join_cols: list[str]) -> pa.Table:
"""
Return a table with rows that need to be updated in the target table based on the join columns.

The table is joined on the identifier columns, and then checked if there are any updated rows.
Those are selected and everything is renamed correctly.
"""
# Scans of files written before a column was added omit that column. Align the target to the
# source so every source column is compared and the join sees matching types.
target_table = _align_to_schema(target_table, source_table.schema)

all_columns = set(source_table.column_names)
join_cols_set = set(join_cols)

Expand All @@ -105,11 +142,9 @@ def get_rows_to_update(source_table: pa.Table, target_table: pa.Table, join_cols
) from None

# Step 1: Prepare source index with join keys and a marker index
# Cast to target table schema, so we can do the join
# See: https://github.com/apache/arrow/issues/37542
source_index = (
source_table.cast(target_table.schema)
.select(join_cols_set)
source_table.select(join_cols_set)
.cast(target_table.select(join_cols_set).schema)
.append_column(SOURCE_INDEX_COLUMN_NAME, pa.array(range(len(source_table))))
)

Expand All @@ -125,9 +160,13 @@ def get_rows_to_update(source_table: pa.Table, target_table: pa.Table, join_cols

changed: pa.Array | pa.ChunkedArray | None = None
for key in non_key_cols:
source_values = source_table.column(key)
target_values = target_table.column(key)
if source_values.type != target_values.type:
source_values = source_values.cast(target_values.type)
column_changed = _values_differ(
source_table.column(key).take(source_indices),
target_table.column(key).take(target_indices),
source_values.take(source_indices),
target_values.take(target_indices),
)
changed = column_changed if changed is None else pc.or_(changed, column_changed)

Expand Down
62 changes: 62 additions & 0 deletions tests/table/test_upsert.py
Original file line number Diff line number Diff line change
Expand Up @@ -198,6 +198,40 @@ def test_merge_scenario_skip_upd_row(catalog: Catalog) -> None:
assert_upsert_result(res, expected_updated, expected_inserted)


def test_merge_after_adding_a_column(catalog: Catalog) -> None:
identifier = "default.test_merge_after_adding_a_column"
_drop_table(catalog, identifier)

df = pa.table({"order_id": [1, 2], "order_type": ["A", "B"]})
table = catalog.create_table(identifier, df.schema)
table.append(df)

with table.update_schema() as update:
update.add_column("ping", StringType())

table = catalog.load_table(identifier)

source_df = pa.table({"order_id": [1], "order_type": ["A"], "ping": ["pong"]})
res = table.upsert(df=source_df, join_cols=["order_id"], when_matched_update_all=True)

assert_upsert_result(res, 1, 0)


def test_merge_float32_update_of_wider_column(catalog: Catalog) -> None:
identifier = "default.test_merge_float32_update_of_wider_column"
_drop_table(catalog, identifier)

df = pa.table({"order_id": [1], "order_value": pa.array([16777217], type=pa.float64())})
table = catalog.create_table(identifier, df.schema)
table.append(df)

source_df = pa.table({"order_id": [1], "order_value": pa.array([16777216], type=pa.float32())})
res = table.upsert(df=source_df, join_cols=["order_id"], when_matched_update_all=True)

assert_upsert_result(res, 1, 0)
assert catalog.load_table(identifier).scan().to_arrow()["order_value"].to_pylist() == [16777216.0]


def test_merge_scenario_date_as_key(catalog: Catalog) -> None:
"""
tests a single insert and update; primary key is a date column
Expand Down Expand Up @@ -955,3 +989,31 @@ def test_get_rows_to_update_compares_nested_values() -> None:
target = pa.table({"pk": [1, 2], "value": pa.array([{"a": 1}, {"a": 3}])})

assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"pk": [2], "value": [{"a": 2}]}


def test_get_rows_to_update_aligns_columns_by_name() -> None:
source = pa.table({"value": [20], "pk": [2]})
target = pa.table({"pk": [2], "value": [10]})

assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"value": [20], "pk": [2]}


def test_get_rows_to_update_adds_source_columns_missing_from_target() -> None:
source = pa.table({"pk": [1], "value": [10], "ping": ["pong"]})
target = pa.table({"pk": [1], "value": [10]})

assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"pk": [1], "value": [10], "ping": ["pong"]}


def test_get_rows_to_update_promotes_columns_before_comparing() -> None:
source = pa.table({"pk": [1], "value": pa.array([16777216], type=pa.float32())})
target = pa.table({"pk": [1], "value": pa.array([16777217], type=pa.float64())})

assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"pk": [1], "value": [16777216.0]}


def test_get_rows_to_update_promotes_join_key_types() -> None:
source = pa.table({"pk": pa.array([1], type=pa.int32()), "value": ["new"]})
target = pa.table({"pk": pa.array([1], type=pa.int64()), "value": ["old"]})

assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"pk": [1], "value": ["new"]}
Loading