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
79 changes: 78 additions & 1 deletion pyiceberg/table/upsert_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
# specific language governing permissions and limitations
# under the License.
import functools
import math
import operator

import pyarrow as pa
Expand Down Expand Up @@ -53,6 +54,78 @@ def has_duplicate_rows(df: pyarrow_table, join_cols: list[str]) -> bool:
return len(df.select(join_cols).group_by(join_cols).aggregate([([], "count_all")]).filter(pc.field("count_all") > 1)) > 0


def _py_struct_field_type(value_type: pa.DataType | None, field_name: object) -> pa.DataType | None:
if not isinstance(field_name, str) or value_type is None or not pa.types.is_struct(value_type):
return None
field_index = value_type.get_field_index(field_name)
if field_index < 0:
return None
return value_type.field(field_index).type


def _py_list_value_type(value_type: pa.DataType | None) -> pa.DataType | None:
if value_type is None:
return None
if pa.types.is_list(value_type):
return value_type.value_type
if pa.types.is_large_list(value_type):
return value_type.value_type
if pa.types.is_fixed_size_list(value_type):
return value_type.value_type
return None


def _py_map_entries_equal(left: object, right: object, map_type: pa.MapType) -> bool:
"""Return whether two maps have the same entries, ignoring entry order."""
if not isinstance(left, list) or not isinstance(right, list) or len(left) != len(right):
return False
pending = [True] * len(right)
for left_entry in left:
if not isinstance(left_entry, tuple) or len(left_entry) != 2:
return False
matched = False
for index, right_entry in enumerate(right):
if not pending[index] or not isinstance(right_entry, tuple) or len(right_entry) != 2:
continue
keys_equal = _py_values_equal(left_entry[0], right_entry[0], map_type.key_type)
values_equal = _py_values_equal(left_entry[1], right_entry[1], map_type.item_type)
if keys_equal and values_equal:
pending[index] = False
matched = True
break
if not matched:
return False
return True


def _py_values_equal(left: object, right: object, value_type: pa.DataType | None) -> bool:
"""Return whether two Python values are equal, treating NaN as equal to NaN."""
# Python equality is false for NaN, and that result propagates through the dicts,
# lists, and tuples from to_pylist(). Null and NaN stay unequal. Map entry order
# is not significant; list order is.
if left is right or left == right:
return True
if isinstance(left, float) and isinstance(right, float) and math.isnan(left) and math.isnan(right):
return True
if isinstance(left, dict) and isinstance(right, dict):
if len(left) != len(right):
return False
for key, left_value in left.items():
field_type = _py_struct_field_type(value_type, key)
if key not in right or not _py_values_equal(left_value, right[key], field_type):
return False
return True
if value_type is not None and pa.types.is_map(value_type) and isinstance(left, list) and isinstance(right, list):
return _py_map_entries_equal(left, right, value_type)
# to_pylist() produces tuples for map entries and lists for list columns.
if isinstance(left, (list, tuple)) and isinstance(right, (list, tuple)):
child_type = _py_list_value_type(value_type)
return len(left) == len(right) and all(
_py_values_equal(left_item, right_item, child_type) for left_item, right_item in zip(left, right, strict=True)
)
return False


def _values_differ(
source_values: pa.Array | pa.ChunkedArray, target_values: pa.Array | pa.ChunkedArray
) -> pa.Array | pa.ChunkedArray:
Expand All @@ -63,8 +136,12 @@ def _values_differ(
# PyArrow has no comparison kernel for nested types
source_list = source_values.to_pylist()
target_list = target_values.to_pylist()
value_type = source_values.type
return pa.array(
[source_value != target_value for source_value, target_value in zip(source_list, target_list, strict=True)],
[
not _py_values_equal(source_value, target_value, value_type)
for source_value, target_value in zip(source_list, target_list, strict=True)
],
type=pa.bool_(),
)

Expand Down
216 changes: 216 additions & 0 deletions tests/table/test_upsert.py
Original file line number Diff line number Diff line change
Expand Up @@ -950,6 +950,222 @@ def test_get_rows_to_update_treats_nulls_as_equal() -> None:
assert get_rows_to_update(source, target, ["pk"]).to_pydict() == {"pk": [2], "value": [1]}


def test_get_rows_to_update_treats_nested_nans_as_equal() -> None:
nan = float("nan")
struct_type = pa.struct([pa.field("a", pa.float64()), pa.field("b", pa.float64())])
list_type = pa.list_(pa.float64())
map_type = pa.map_(pa.string(), pa.float64())
mixed_type = pa.struct(
[
pa.field("label", pa.string()),
pa.field("samples", pa.list_(pa.float64())),
pa.field("point", pa.struct([pa.field("x", pa.float64())])),
]
)
# Each case keeps one row that differs only by nested NaN, and one row with a real change.
cases = [
(
"struct",
pa.array([{"a": nan, "b": 1.0}, {"a": nan, "b": 1.0}], type=struct_type),
pa.array([{"a": nan, "b": 1.0}, {"a": nan, "b": 2.0}], type=struct_type),
[2],
),
(
"list",
pa.array([[nan, 1.0, None], [nan, 1.0]], type=list_type),
pa.array([[nan, 1.0, None], [nan, 2.0]], type=list_type),
[2],
),
(
"map",
pa.array([[("k", nan), ("m", 1.0)], [("k", nan)]], type=map_type),
pa.array([[("k", nan), ("m", 1.0)], [("k", 2.0)]], type=map_type),
[2],
),
(
"mixed",
pa.array(
[
{"label": "same", "samples": [nan, None], "point": {"x": nan}},
{"label": "edit", "samples": [nan], "point": {"x": 1.0}},
],
type=mixed_type,
),
pa.array(
[
{"label": "same", "samples": [nan, None], "point": {"x": nan}},
{"label": "edit", "samples": [1.0], "point": {"x": 1.0}},
],
type=mixed_type,
),
[2],
),
]
for name, source_values, target_values, expected_pks in cases:
source = pa.table({"pk": [1, 2], "value": source_values})
target = pa.table({"pk": [1, 2], "value": target_values})
updated_pks = get_rows_to_update(source, target, ["pk"]).column("pk").to_pylist()
assert sorted(updated_pks) == expected_pks, name


def test_get_rows_to_update_ignores_map_entry_order() -> None:
nan = float("nan")
map_type = pa.map_(pa.string(), pa.float64())
list_type = pa.list_(pa.float64())
nested_type = pa.struct([pa.field("scores", map_type)])
# Reordered map entries are the same value. List order still counts as a change.
cases = [
(
"map",
pa.array([[("k", nan), ("m", 1.0)], [("a", 1.0), ("b", nan)]], type=map_type),
pa.array([[("m", 1.0), ("k", nan)], [("b", 2.0), ("a", 1.0)]], type=map_type),
[2],
),
(
"list",
pa.array([[nan, 1.0], [1.0, 2.0]], type=list_type),
pa.array([[1.0, nan], [1.0, 2.0]], type=list_type),
[1],
),
(
"nested-map",
pa.array(
[{"scores": [("k", nan), ("m", 1.0)]}, {"scores": [("a", 1.0)]}],
type=nested_type,
),
pa.array(
[{"scores": [("m", 1.0), ("k", nan)]}, {"scores": [("a", 2.0)]}],
type=nested_type,
),
[2],
),
]
for name, source_values, target_values, expected_pks in cases:
source = pa.table({"pk": [1, 2], "value": source_values})
target = pa.table({"pk": [1, 2], "value": target_values})
updated_pks = get_rows_to_update(source, target, ["pk"]).column("pk").to_pylist()
assert sorted(updated_pks) == expected_pks, name


def test_get_rows_to_update_detects_nested_nan_transitions() -> None:
nan = float("nan")
struct_type = pa.struct([pa.field("a", pa.float64())])
list_type = pa.list_(pa.float64())
mixed_type = pa.struct(
[
pa.field("samples", pa.list_(pa.float64())),
pa.field("point", pa.struct([pa.field("x", pa.float64())])),
]
)
# number -> NaN, NaN -> number, null -> NaN, NaN -> null, and one NaN -> NaN row that is unchanged.
cases = [
(
"struct",
pa.array([{"a": 1.0}, {"a": nan}, {"a": None}, {"a": nan}, {"a": nan}], type=struct_type),
pa.array([{"a": nan}, {"a": 2.0}, {"a": nan}, {"a": None}, {"a": nan}], type=struct_type),
[1, 2, 3, 4],
),
(
"list",
pa.array([[1.0], [nan], [None], [nan], [nan]], type=list_type),
pa.array([[nan], [2.0], [nan], [None], [nan]], type=list_type),
[1, 2, 3, 4],
),
(
"mixed",
pa.array(
[
{"samples": [1.0], "point": {"x": 1.0}},
{"samples": [nan], "point": {"x": nan}},
{"samples": [None], "point": {"x": None}},
{"samples": [nan], "point": {"x": nan}},
{"samples": [nan], "point": {"x": nan}},
],
type=mixed_type,
),
pa.array(
[
{"samples": [nan], "point": {"x": 1.0}},
{"samples": [nan], "point": {"x": 2.0}},
{"samples": [nan], "point": {"x": None}},
{"samples": [None], "point": {"x": nan}},
{"samples": [nan], "point": {"x": nan}},
],
type=mixed_type,
),
[1, 2, 3, 4],
),
]
for name, source_values, target_values, expected_pks in cases:
source = pa.table({"pk": [1, 2, 3, 4, 5], "value": source_values})
target = pa.table({"pk": [1, 2, 3, 4, 5], "value": target_values})
updated_pks = get_rows_to_update(source, target, ["pk"]).column("pk").to_pylist()
assert sorted(updated_pks) == expected_pks, name


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

arrow_schema = pa.schema(
[
pa.field("id", pa.int32(), nullable=False),
pa.field("point", pa.struct([pa.field("x", pa.float64()), pa.field("y", pa.float64())])),
pa.field("samples", pa.list_(pa.float64())),
pa.field(
"reading",
pa.struct(
[
pa.field("value", pa.float64()),
pa.field("history", pa.list_(pa.struct([pa.field("v", pa.float64())]))),
]
),
),
]
)
nan = float("nan")
rows = [
{
"id": 1,
"point": {"x": 1.0, "y": nan},
"samples": [nan, 1.0],
"reading": {"value": nan, "history": [{"v": nan}, {"v": 1.0}]},
},
{
"id": 2,
"point": None,
"samples": None,
"reading": {"value": None, "history": None},
},
{
"id": 3,
"point": {"x": nan, "y": None},
"samples": [None, nan],
"reading": {"value": 2.0, "history": [{"v": None}]},
},
]
df = pa.Table.from_pylist(rows, schema=arrow_schema)
tbl = catalog.create_table(identifier, arrow_schema)
tbl.append(df)
assert len(list(tbl.snapshots())) == 1

res = tbl.upsert(df, join_cols=["id"])

assert_upsert_result(res, 0, 0)
assert len(list(tbl.snapshots())) == 1

changed_rows = [
{
"id": 1,
"point": {"x": 1.0, "y": nan},
"samples": [nan, 1.0],
"reading": {"value": nan, "history": [{"v": 4.0}, {"v": 1.0}]},
}
]
res = tbl.upsert(pa.Table.from_pylist(changed_rows, schema=arrow_schema), join_cols=["id"])
assert_upsert_result(res, 1, 0)


def test_get_rows_to_update_compares_nested_values() -> None:
source = pa.table({"pk": [1, 2], "value": pa.array([{"a": 1}, {"a": 2}])})
target = pa.table({"pk": [1, 2], "value": pa.array([{"a": 1}, {"a": 3}])})
Expand Down
Loading