Fokko commented on code in PR #4449:
URL: https://github.com/apache/iceberg-python/pull/4449#discussion_r4717877693


##########
pyiceberg/io/pyarrow.py:
##########
@@ -3333,13 +3327,74 @@ def _dataframe_to_data_files(
                     write_uuid=write_uuid,
                     task_id=next(counter),
                     record_batches=batches,
-                    partition_key=partition.partition_key,
                     schema=task_schema,
+                    sort_order_id=sort_order_id,
                 )
-                for partition in partitions
-                for batches in 
bin_pack_arrow_table(partition.arrow_table_partition, target_file_size)
+                for batches in bin_pack_arrow_table(sorted_df, 
target_file_size)
             ),
         )
+    else:
+        partitions = _determine_partitions(spec=table_metadata.spec(), 
schema=table_metadata.schema(), arrow_table=df)
+
+        def _tasks() -> Iterator[WriteTask]:
+            for partition in partitions:
+                sorted_partition, sort_order_id = 
_sort_table_for_write(table_metadata, partition.arrow_table_partition)
+                for batches in bin_pack_arrow_table(sorted_partition, 
target_file_size):
+                    yield WriteTask(
+                        write_uuid=write_uuid,
+                        task_id=next(counter),
+                        record_batches=batches,
+                        partition_key=partition.partition_key,
+                        schema=task_schema,
+                        sort_order_id=sort_order_id,
+                    )
+
+        yield from write_file(io=io, table_metadata=table_metadata, 
tasks=_tasks())
+
+
+def _sort_table_for_write(table_metadata: TableMetadata, table: pa.Table) -> 
tuple[pa.Table, int | None]:
+    """Sort the table for the table's sort order and return its file 
sort-order id.
+
+    Returns the table unchanged and ``None`` when the sort order cannot be 
applied, so the
+    written files are marked unsorted.
+    """
+    sort_order = table_metadata.sort_order()
+    if sort_order.is_unsorted:
+        return table, None
+
+    schema = table_metadata.schema()
+    sort_key_pairs: list[tuple[str, str]] = []
+    null_orders: set[NullOrder] = set()
+    for sort_field in sort_order.fields:
+        if not isinstance(sort_field.transform, IdentityTransform):
+            warnings.warn(
+                f"Sort transform {sort_field.transform} is not supported for 
writes; data files are marked unsorted",
+                stacklevel=2,
+            )
+            return table, None
+        column_name = schema.find_column_name(sort_field.source_id)
+        if column_name is None or column_name not in table.column_names:
+            warnings.warn(
+                f"Sort field with source id {sort_field.source_id} refers to a 
nested or missing column; "
+                "data files are marked unsorted",
+                stacklevel=2,
+            )
+            return table, None
+        sort_key_pairs.append((column_name, "descending" if 
sort_field.direction == SortDirection.DESC else "ascending"))
+        null_orders.add(sort_field.null_order)
+
+    if len(null_orders) != 1:
+        warnings.warn("Mixed null ordering is not supported for writes; data 
files are marked unsorted", stacklevel=2)
+        return table, None
+
+    null_placement = "at_start" if NullOrder.NULLS_FIRST in null_orders else 
"at_end"

Review Comment:
   Arrow keeps NaN next to the nulls, so it follows `null_placement` instead of 
the Iceberg float ordering (`-NaN < -Inf < ... < Inf < NaN`). Sorting `[1.0, 
nan, None, -1.0, inf]` on pyarrow 26:
   
   | order | Arrow | spec |
   |---|---|---|
   | ASC, NULLS_LAST | `[-1, 1, inf, nan, None]` | same |
   | ASC, NULLS_FIRST | `[None, nan, -1, 1, inf]` | `[None, -1, 1, inf, nan]` |
   | DESC, NULLS_LAST | `[inf, 1, -1, nan, None]` | `[nan, inf, 1, -1, None]` |
   | DESC, NULLS_FIRST | `[None, nan, inf, 1, -1]` | same |
   
   For ASC NULLS_FIRST and DESC NULLS_LAST on a float/double column, the files 
get a `sort_order_id` they don't satisfy. Could we fall back to unsorted with a 
warning for those combinations, and add a NaN case to the tests?
   



-- 
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: [email protected]

For queries about this service, please contact Infrastructure at:
[email protected]


---------------------------------------------------------------------
To unsubscribe, e-mail: [email protected]
For additional commands, e-mail: [email protected]

Reply via email to