tscottcoombes1 commented on code in PR #1534: URL: https://github.com/apache/iceberg-python/pull/1534#discussion_r1940230399
########## tests/table/test_merge_rows.py: ########## @@ -0,0 +1,397 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyiceberg.catalog.sql import SqlCatalog +import os +import shutil + +_TEST_NAMESPACE = "test_ns" + +try: + from datafusion import SessionContext +except ModuleNotFoundError as e: + raise ModuleNotFoundError("For merge_rows, DataFusion needs to be installed") from e + +def get_test_warehouse_path(): + curr_dir = os.path.dirname(os.path.abspath(__file__)) + return f"{curr_dir}/warehouse" + +def get_sql_catalog(namespace: str) -> SqlCatalog: + warehouse_path = get_test_warehouse_path() + catalog = SqlCatalog( + "default", + **{ + "uri": f"sqlite:///:memory:", + "warehouse": f"file://{warehouse_path}", + }, + ) + + catalog.create_namespace(namespace=namespace) + return catalog + +def purge_warehouse(): + warehouse_path = get_test_warehouse_path() + + if os.path.exists(warehouse_path): + shutil.rmtree(warehouse_path) + +def show_iceberg_table(table, ctx: SessionContext): + import pyarrow.dataset as ds + table_name = "target" + if ctx.table_exist(table_name): + ctx.deregister_table(table_name) + ctx.register_dataset(table_name, ds.dataset(table.scan().to_arrow())) + ctx.sql(f"SELECT * FROM {table_name} limit 5").show() + +def show_df(df, ctx: SessionContext): + import pyarrow.dataset as ds + ctx.register_dataset("df", ds.dataset(df)) + ctx.sql("select * from df limit 10").show() + +def gen_source_dataset(start_row: int, end_row: int, composite_key: bool, add_dup: bool, ctx: SessionContext): + + additional_columns = ", t.order_id + 1000 as order_line_id" if composite_key else "" + + dup_row = f""" + UNION ALL + ( + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'B' as order_type + from t + limit 1 + ) + """ if add_dup else "" + + + sql = f""" + with t as (SELECT unnest(range({start_row},{end_row+1})) as order_id) + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'B' as order_type + from t + {dup_row} + """ + + #print(sql) + + df = ctx.sql(sql).to_arrow_table() + + + return df + +def gen_target_iceberg_table(start_row: int, end_row: int, composite_key: bool, ctx: SessionContext): + + additional_columns = ", t.order_id + 1000 as order_line_id" if composite_key else "" + + df = ctx.sql(f""" + with t as (SELECT unnest(range({start_row},{end_row+1})) as order_id) + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'A' as order_type + from t + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + return table + +def test_merge_scenario_1a_simple(): + + """ + tests a single insert and update + """ + + ctx = SessionContext() + + table = gen_target_iceberg_table(1, 2, False, ctx) + source_df = gen_source_dataset(2, 3, False, False, ctx) + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1a pass') + +def test_merge_scenario_1b_simple(): + + """ + tests a single insert and update; skips a row that does not need to be updated + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select 1 as order_id, date '2021-01-01' as order_date, 'A' as order_type + union all + select 2 as order_id, date '2021-01-01' as order_date, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select 1 as order_id, date '2021-01-01' as order_date, 'A' as order_type + union all + select 2 as order_id, date '2021-01-01' as order_date, 'B' as order_type + union all + select 3 as order_id, date '2021-01-01' as order_date, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1b (skip 1 row) pass') + + +def test_merge_scenario_1c_simple(): + + """ + tests a single insert and update; primary key is a date column + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select date '2021-01-01' as order_date, 'A' as order_type + union all + select date '2021-01-02' as order_date, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select date '2021-01-01' as order_date, 'A' as order_type + union all + select date '2021-01-02' as order_date, 'B' as order_type + union all + select date '2021-01-03' as order_date, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_date"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1c (date as key column) pass') + +def test_merge_scenario_1d_simple(): + + """ + tests a single insert and update; primary key is a string column + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select 'abc' as order_id, 'A' as order_type + union all + select 'def' as order_id, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select 'abc' as order_id, 'A' as order_type + union all + select 'def' as order_id, 'B' as order_type + union all + select 'ghi' as order_id, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1d (string as key column) pass') + +def test_merge_scenario_2_10k_rows(): + + """ + tests merging 10000 rows on a single key to simulate larger workload + """ + + ctx = SessionContext() + + table = gen_target_iceberg_table(1, 10000, False, ctx) + source_df = gen_source_dataset(5001, 15000, False, False, ctx) + + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 5000 + rows_inserted_should_be = 5000 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() Review Comment: you can use the existing `catalog: SqlCatalog` fixture (which is in memory), and then remove this function. you can also use pytest.mark.parameterise to tidy up scenarios 1 through 3 You can keep the tables in here small in size. There is a `test_benchmark.py` file that includes large data sets, if you want to be testing 10k rows of data. ########## tests/table/test_merge_rows.py: ########## @@ -0,0 +1,397 @@ +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. + +from pyiceberg.catalog.sql import SqlCatalog +import os +import shutil + +_TEST_NAMESPACE = "test_ns" + +try: + from datafusion import SessionContext +except ModuleNotFoundError as e: + raise ModuleNotFoundError("For merge_rows, DataFusion needs to be installed") from e + +def get_test_warehouse_path(): + curr_dir = os.path.dirname(os.path.abspath(__file__)) + return f"{curr_dir}/warehouse" + +def get_sql_catalog(namespace: str) -> SqlCatalog: + warehouse_path = get_test_warehouse_path() + catalog = SqlCatalog( + "default", + **{ + "uri": f"sqlite:///:memory:", + "warehouse": f"file://{warehouse_path}", + }, + ) + + catalog.create_namespace(namespace=namespace) + return catalog + +def purge_warehouse(): + warehouse_path = get_test_warehouse_path() + + if os.path.exists(warehouse_path): + shutil.rmtree(warehouse_path) + +def show_iceberg_table(table, ctx: SessionContext): + import pyarrow.dataset as ds + table_name = "target" + if ctx.table_exist(table_name): + ctx.deregister_table(table_name) + ctx.register_dataset(table_name, ds.dataset(table.scan().to_arrow())) + ctx.sql(f"SELECT * FROM {table_name} limit 5").show() + +def show_df(df, ctx: SessionContext): + import pyarrow.dataset as ds + ctx.register_dataset("df", ds.dataset(df)) + ctx.sql("select * from df limit 10").show() + +def gen_source_dataset(start_row: int, end_row: int, composite_key: bool, add_dup: bool, ctx: SessionContext): + + additional_columns = ", t.order_id + 1000 as order_line_id" if composite_key else "" + + dup_row = f""" + UNION ALL + ( + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'B' as order_type + from t + limit 1 + ) + """ if add_dup else "" + + + sql = f""" + with t as (SELECT unnest(range({start_row},{end_row+1})) as order_id) + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'B' as order_type + from t + {dup_row} + """ + + #print(sql) + + df = ctx.sql(sql).to_arrow_table() + + + return df + +def gen_target_iceberg_table(start_row: int, end_row: int, composite_key: bool, ctx: SessionContext): + + additional_columns = ", t.order_id + 1000 as order_line_id" if composite_key else "" + + df = ctx.sql(f""" + with t as (SELECT unnest(range({start_row},{end_row+1})) as order_id) + SELECT t.order_id {additional_columns} + , date '2021-01-01' as order_date, 'A' as order_type + from t + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + return table + +def test_merge_scenario_1a_simple(): + + """ + tests a single insert and update + """ + + ctx = SessionContext() + + table = gen_target_iceberg_table(1, 2, False, ctx) + source_df = gen_source_dataset(2, 3, False, False, ctx) + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1a pass') + +def test_merge_scenario_1b_simple(): + + """ + tests a single insert and update; skips a row that does not need to be updated + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select 1 as order_id, date '2021-01-01' as order_date, 'A' as order_type + union all + select 2 as order_id, date '2021-01-01' as order_date, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select 1 as order_id, date '2021-01-01' as order_date, 'A' as order_type + union all + select 2 as order_id, date '2021-01-01' as order_date, 'B' as order_type + union all + select 3 as order_id, date '2021-01-01' as order_date, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1b (skip 1 row) pass') + + +def test_merge_scenario_1c_simple(): + + """ + tests a single insert and update; primary key is a date column + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select date '2021-01-01' as order_date, 'A' as order_type + union all + select date '2021-01-02' as order_date, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select date '2021-01-01' as order_date, 'A' as order_type + union all + select date '2021-01-02' as order_date, 'B' as order_type + union all + select date '2021-01-03' as order_date, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_date"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1c (date as key column) pass') + +def test_merge_scenario_1d_simple(): + + """ + tests a single insert and update; primary key is a string column + """ + + ctx = SessionContext() + + df = ctx.sql(f""" + select 'abc' as order_id, 'A' as order_type + union all + select 'def' as order_id, 'A' as order_type + """).to_arrow_table() + + catalog = get_sql_catalog(_TEST_NAMESPACE) + table = catalog.create_table(f"{_TEST_NAMESPACE}.target", df.schema) + + table.append(df) + + source_df = ctx.sql(f""" + select 'abc' as order_id, 'A' as order_type + union all + select 'def' as order_id, 'B' as order_type + union all + select 'ghi' as order_id, 'A' as order_type + """).to_arrow_table() + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 1 + rows_inserted_should_be = 1 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 1d (string as key column) pass') + +def test_merge_scenario_2_10k_rows(): + + """ + tests merging 10000 rows on a single key to simulate larger workload + """ + + ctx = SessionContext() + + table = gen_target_iceberg_table(1, 10000, False, ctx) + source_df = gen_source_dataset(5001, 15000, False, False, ctx) + + + res = table.merge_rows(df=source_df, join_cols=["order_id"]) + + rows_updated_should_be = 5000 + rows_inserted_should_be = 5000 + + assert res['rows_updated'] == rows_updated_should_be, f"rows updated should be {rows_updated_should_be}, but got {res['rows_updated']}" + assert res['rows_inserted'] == rows_inserted_should_be, f"rows inserted should be {rows_inserted_should_be}, but got {res['rows_inserted']}" + + purge_warehouse() + print('merge rows: test scenario 2 pass') Review Comment: you can remove these print statements, pytest will tell you if the test passes ########## pyiceberg/table/merge_rows_util.py: ########## @@ -0,0 +1,143 @@ + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from pyarrow import Table as pyarrow_table +import pyarrow as pa +from pyarrow import compute as pc +from pyiceberg import table as pyiceberg_table + +from pyiceberg.expressions import ( + BooleanExpression, + And, + EqualTo, + Or, + In, +) + +def get_filter_list(df: pyarrow_table, join_cols: list) -> BooleanExpression: + + unique_keys = df.select(join_cols).group_by(join_cols).aggregate([]) + + pred = None + + if len(join_cols) == 1: + pred = In(join_cols[0], unique_keys[0].to_pylist()) + else: + pred = Or(*[ + And(*[ + EqualTo(col, row[col]) + for col in join_cols + ]) + for row in unique_keys.to_pylist() + ]) + + return pred + + +def get_table_column_list_pa(df: pyarrow_table) -> list: + return set(col for col in df.column_names) + +def get_table_column_list_iceberg(table: pyiceberg_table) -> list: + return set(col for col in table.schema().column_names) + +def dups_check_in_source(df: pyarrow_table, join_cols: list) -> bool: + """ + This function checks if there are duplicate rows in the source table based on the join columns. + It returns True if there are duplicate rows in the source table, otherwise it returns False. + """ + # Check for duplicates in the source table Review Comment: you don't need this comment if you have a nice docstring, and a well named function 😄 ########## pyiceberg/table/merge_rows_util.py: ########## @@ -0,0 +1,143 @@ + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from pyarrow import Table as pyarrow_table +import pyarrow as pa +from pyarrow import compute as pc +from pyiceberg import table as pyiceberg_table + +from pyiceberg.expressions import ( + BooleanExpression, + And, + EqualTo, + Or, + In, +) + +def get_filter_list(df: pyarrow_table, join_cols: list) -> BooleanExpression: + + unique_keys = df.select(join_cols).group_by(join_cols).aggregate([]) + + pred = None + + if len(join_cols) == 1: + pred = In(join_cols[0], unique_keys[0].to_pylist()) + else: + pred = Or(*[ + And(*[ + EqualTo(col, row[col]) + for col in join_cols + ]) + for row in unique_keys.to_pylist() + ]) + + return pred + + +def get_table_column_list_pa(df: pyarrow_table) -> list: + return set(col for col in df.column_names) + +def get_table_column_list_iceberg(table: pyiceberg_table) -> list: + return set(col for col in table.schema().column_names) Review Comment: same as above, pyiceberg.table.schema.column_names is already a list(str) ########## pyiceberg/table/merge_rows_util.py: ########## @@ -0,0 +1,143 @@ + +# Licensed to the Apache Software Foundation (ASF) under one +# or more contributor license agreements. See the NOTICE file +# distributed with this work for additional information +# regarding copyright ownership. The ASF licenses this file +# to you under the Apache License, Version 2.0 (the +# "License"); you may not use this file except in compliance +# with the License. You may obtain a copy of the License at +# +# http://www.apache.org/licenses/LICENSE-2.0 +# +# Unless required by applicable law or agreed to in writing, +# software distributed under the License is distributed on an +# "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY +# KIND, either express or implied. See the License for the +# specific language governing permissions and limitations +# under the License. +from pyarrow import Table as pyarrow_table +import pyarrow as pa +from pyarrow import compute as pc +from pyiceberg import table as pyiceberg_table + +from pyiceberg.expressions import ( + BooleanExpression, + And, + EqualTo, + Or, + In, +) + +def get_filter_list(df: pyarrow_table, join_cols: list) -> BooleanExpression: + + unique_keys = df.select(join_cols).group_by(join_cols).aggregate([]) + + pred = None + + if len(join_cols) == 1: + pred = In(join_cols[0], unique_keys[0].to_pylist()) + else: + pred = Or(*[ + And(*[ + EqualTo(col, row[col]) + for col in join_cols + ]) + for row in unique_keys.to_pylist() + ]) + + return pred + + +def get_table_column_list_pa(df: pyarrow_table) -> list: Review Comment: pa.Table.column_names already returns list(str) https://arrow.apache.org/docs/python/generated/pyarrow.Table.html#pyarrow.Table.column_names you can remove this. If it it important to return a `set` then you can change the typing -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For queries about this service, please contact Infrastructure at: us...@infra.apache.org --------------------------------------------------------------------- To unsubscribe, e-mail: issues-unsubscr...@iceberg.apache.org For additional commands, e-mail: issues-h...@iceberg.apache.org