Skip to content

fix upsert with null values #1861

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Mar 31, 2025
Merged
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: 10 additions & 1 deletion pyiceberg/table/upsert_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -65,7 +65,16 @@ def get_rows_to_update(source_table: pa.Table, target_table: pa.Table, join_cols
# When the target table is empty, there is nothing to update :)
return source_table.schema.empty_table()

diff_expr = functools.reduce(operator.or_, [pc.field(f"{col}-lhs") != pc.field(f"{col}-rhs") for col in non_key_cols])
diff_expr = functools.reduce(
operator.or_,
[
pc.or_kleene(
pc.not_equal(pc.field(f"{col}-lhs"), pc.field(f"{col}-rhs")),
pc.is_null(pc.not_equal(pc.field(f"{col}-lhs"), pc.field(f"{col}-rhs"))),
)
for col in non_key_cols
],
)

return (
source_table
Expand Down
43 changes: 43 additions & 0 deletions tests/table/test_upsert.py
Original file line number Diff line number Diff line change
Expand Up @@ -509,3 +509,46 @@ def test_upsert_without_identifier_fields(catalog: Catalog) -> None:
ValueError, match="Join columns could not be found, please set identifier-field-ids or pass in explicitly."
):
tbl.upsert(df)


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

schema = pa.schema(
[
("foo", pa.string()),
("bar", pa.int32()),
("baz", pa.bool_()),
]
)

# create table with null value
table = catalog.create_table(identifier, schema)
data_with_null = pa.Table.from_pylist(
[
{"foo": "apple", "bar": None, "baz": False},
{"foo": "banana", "bar": None, "baz": False},
],
schema=schema,
)
table.append(data_with_null)
assert table.scan().to_arrow()["bar"].is_null()

# upsert table with non-null value
data_without_null = pa.Table.from_pylist(
[
{"foo": "apple", "bar": 7, "baz": False},
],
schema=schema,
)
upd = table.upsert(data_without_null, join_cols=["foo"])
assert upd.rows_updated == 1
assert upd.rows_inserted == 0
assert table.scan().to_arrow() == pa.Table.from_pylist(
[
{"foo": "apple", "bar": 7, "baz": False},
{"foo": "banana", "bar": None, "baz": False},
],
schema=schema,
)