tscottcoombes1 commented on code in PR #1534:
URL: https://github.com/apache/iceberg-python/pull/1534#discussion_r1941888231


##########
tests/table/test_merge_rows.py:
##########
@@ -0,0 +1,380 @@
+# 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}
+    """
+
+    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_single_ins_upd():
+
+    """
+        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()
+
+def test_merge_scenario_skip_upd_row():

Review Comment:
   with parameterisation:
   
   ```
   import pytest
   import pyarrow as pa
   import pandas as pd
   import datetime
   import string
   
   
   def sample_table(num_rows: int = 100, start_at: int = 0) -> pa.Table:
       start_date = datetime.date(2000, 1, 1) + datetime.timedelta(start_at)
       alphabet = list(string.ascii_uppercase)
       _range = range(start_at, start_at + num_rows)
   
       df = pd.DataFrame(
           {
               'int_col': list(_range),
               "date_col": list(pd.date_range(start=start_date, end=start_date 
+ datetime.timedelta(days=num_rows-1), freq="D")),
               "str_col": [alphabet[i % 26] for i in _range]
           }
       )
   
       return pa.Table.from_pandas(df)
   
   
   @pytest.mark.parametrize(
       
"tbl_1,tbl_2,join_cols,insert_all,update_all,expected_row_inserts,expected_row_updates",
       [
           # test different join cols
           (sample_table(26), sample_table(26,13), ["int_col"], None, None, 13, 
13),
           (sample_table(26), sample_table(26,13), ["date_col"], None, None, 
13, 13),
           (sample_table(26), sample_table(26,13), ["str_col"], None, None, 0, 
26),
           # test different match inputs
           (sample_table(26), sample_table(26,13), ["int_col"], True, None, 13, 
13),
           (sample_table(26), sample_table(26,13), ["int_col"], False, None, 0, 
13),
           (sample_table(26), sample_table(26,13), ["int_col"], None, True, 13, 
13),
           (sample_table(26), sample_table(26,13), ["int_col"], None, False, 
13, 0),
           (sample_table(26), sample_table(26,13), ["int_col"], True, True, 13, 
13),
           (sample_table(26), sample_table(26,13), ["int_col"], True, False, 
13, 0),
           (sample_table(26), sample_table(26,13), ["int_col"], False, True, 0, 
13),
           (sample_table(26), sample_table(26,13), ["int_col"], False, False, 
0, 0),
       ],
   
   )
   def 
test_merge_rows(tbl_1,tbl_2,join_cols,insert_all,update_all,expected_row_inserts,expected_row_updates):
       """
       Test the merge rows functionality
       """
       res = tbl_1.merge_rows(
           df=tbl_2,
           join_cols=join_cols,
           when_matched_update_all = update_all,
           when_not_matched_insert_all = insert_all
       )
   
       assert res.rows_updated == expected_row_inserts
       assert res.rows_inserted == expected_row_updates
   ```



-- 
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

Reply via email to