laskoviymishka commented on code in PR #2660:
URL: https://github.com/apache/iceberg-go/pull/2660#discussion_r4687832369


##########
table/replace_sort_order_builder.go:
##########
@@ -53,23 +53,17 @@ func NewReplaceSortOrderBuilder(t *Transaction, 
caseSensitive bool) *ReplaceSort
 }
 
 // Asc adds a column sorted in ascending order with the requested null 
ordering.
-// Go writers currently support only top-level sort columns; appending data 
with
-// a nested-field sort order fails until the order is replaced.
 func (u *ReplaceSortOrderBuilder) Asc(column string, nullOrder NullOrder) 
*ReplaceSortOrderBuilder {
        return u.AddField(column, iceberg.IdentityTransform{}, SortASC, 
nullOrder)
 }
 
 // Desc adds a column sorted in descending order with the requested null 
ordering.
-// Go writers currently support only top-level sort columns; appending data 
with
-// a nested-field sort order fails until the order is replaced.
 func (u *ReplaceSortOrderBuilder) Desc(column string, nullOrder NullOrder) 
*ReplaceSortOrderBuilder {
        return u.AddField(column, iceberg.IdentityTransform{}, SortDESC, 
nullOrder)
 }
 
 // AddField adds a transformed sort field. A nil or incompatible transform is
-// rejected when the replacement is applied or committed. Go writers currently
-// support only top-level sort columns; appending data with a nested-field sort
-// order fails until the order is replaced.
+// rejected when the replacement is applied or committed.

Review Comment:
   Should `Apply` also reject a source nested under a list or map, now that 
`sortFieldPath` tells the two apart? As I read it, 
[`CheckCompatibility`](https://github.com/apache/iceberg-go/blob/2dc6c84488b78e2fe8e135b79ef3d53a27f8fd08/table/sorting.go#L479-L515)
 only checks that the leaf is primitive, so such an order commits and every 
later append then fails in 
[`newWriterFactory`](https://github.com/apache/iceberg-go/blob/2dc6c84488b78e2fe8e135b79ef3d53a27f8fd08/table/rolling_data_writer.go#L273-L282).
 `main` behaves the same, but the caveat removed here was the only warning 
about it.



##########
table/rolling_data_writer_test.go:
##########
@@ -964,6 +938,134 @@ func (s *RollingDataWriterTestSuite) 
TestSortsRowsBeforeWriting() {
        s.Equal(want, got)
 }
 
+// sortedWriterFactory returns a writer factory for an unpartitioned table
+// of arrSchema whose default sort order has fields built by sortFields
+// from the table schema.
+func (s *RollingDataWriterTestSuite) sortedWriterFactory(
+       arrSchema *arrow.Schema, sortFields func(*iceberg.Schema) []SortField,
+) (*writerFactory, error) {
+       icebergSchema, err := ArrowSchemaToIcebergWithFreshIDs(arrSchema, false)
+       s.Require().NoError(err)
+       sortOrder, err := NewSortOrder(1, sortFields(icebergSchema))
+       s.Require().NoError(err)
+
+       loc := filepath.ToSlash(s.T().TempDir())
+       spec := iceberg.NewPartitionSpec()
+       meta, err := NewMetadata(icebergSchema, &spec, UnsortedSortOrder, loc, 
iceberg.Properties{})
+       s.Require().NoError(err)
+       metaBuilder, err := MetadataBuilderFromBase(meta, "")
+       s.Require().NoError(err)
+       s.Require().NoError(metaBuilder.AddSortOrder(&sortOrder))
+       s.Require().NoError(metaBuilder.SetDefaultSortOrderID(-1))
+
+       writeUUID := uuid.New()
+       args := recordWritingArgs{
+               sc:        arrSchema,
+               fs:        iceio.LocalFS{},
+               writeUUID: &writeUUID,
+               counter: func(yield func(int) bool) {
+                       for i := 0; ; i++ {
+                               if !yield(i) {
+                                       break
+                               }
+                       }
+               },
+       }
+
+       return newWriterFactory(loc, args, metaBuilder, icebergSchema, 
1024*1024)
+}
+
+// TestSortsRowsByNestedKeyBeforeWriting sorts on write by a struct child.
+// A row whose struct is null sorts as a null key even though the child
+// array holds a value in its slot.
+func (s *RollingDataWriterTestSuite) TestSortsRowsByNestedKeyBeforeWriting() {

Review Comment:
   Could we add one writer-level case where the input struct children come in a 
different order than the table schema, ideally with a mixed order and a nested 
`DESC` key? `TestSortRecordBatchMatchesRowComparator` covers those orders on 
`sortRecordBatch`, but the writer resolves paths against `f.arrowSchema` and 
applies them after `toRequestedSchema`, and this test is the only one that goes 
through that step, with one `ASC` key and matching schemas.



##########
table/sort_keys.go:
##########
@@ -78,3 +94,255 @@ func topLevelFieldIndex(fields []iceberg.NestedField, 
sourceID int) (int, bool)
 
        return 0, false
 }
+
+// allTopLevelSortSources reports whether every source of order is a
+// top-level column of fields. Only then can Arrow's sort kernel order a
+// batch by it directly; otherwise the writer uses sortRecordBatch.
+func allTopLevelSortSources(order SortOrder, fields []iceberg.NestedField) 
bool {
+       for _, field := range order.fields {
+               if _, ok := topLevelFieldIndex(fields, field.FirstSourceID()); 
!ok {
+                       return false
+               }
+       }
+
+       return true
+}
+
+// sortFieldPath returns the struct-index path through fields, the top-level
+// fields of schema, to the column sourceID.
+func sortFieldPath(schema *iceberg.Schema, fields []iceberg.NestedField, 
sourceID, orderID int) ([]int, error) {
+       if path, ok := structFieldPath(fields, sourceID); ok {
+               return path, nil
+       }
+       if _, ok := schema.FindFieldByID(sourceID); ok {
+               return nil, fmt.Errorf("%w: sort order %d: source id %d is 
nested under a list or map",
+                       iceberg.ErrInvalidArgument, orderID, sourceID)
+       }
+
+       return nil, fmt.Errorf("sort order %d: source id %d is not a column in 
schema", orderID, sourceID)

Review Comment:
   The list/map case above wraps `iceberg.ErrInvalidArgument` and this one 
doesn't, so only one of the two matches `errors.Is`. `CheckCompatibility` makes 
this path hard to reach, so this is only for consistency.
   
   ```suggestion
        return nil, fmt.Errorf("%w: sort order %d: source id %d is not a column 
in schema", iceberg.ErrInvalidArgument, orderID, sourceID)
   ```



##########
table/sort_compaction.go:
##########
@@ -168,32 +207,47 @@ func (c rowComparator) compare(a arrow.RecordBatch, i 
int, b arrow.RecordBatch,
 // key column's typed values once instead of on every comparison.
 func (c rowComparator) bind(batches []arrow.RecordBatch) func(x, y rowRef) int 
{
        type boundKey struct {
-               cols       []arrow.Array
+               // chains[b] is the key's path through batches[b]; see
+               // sortKeyColumn.chain.
+               chains     [][]arrow.Array
                hasNulls   bool
                desc       bool
                nullsFirst bool
                compare    func(xb, xi, yb, yi int) int
        }
+       isNull := func(chain []arrow.Array, row int) bool {

Review Comment:
   With `hasNulls` set, every comparison now walks the whole chain, including 
the length-1 chains of top-level keys in sort compaction, where `main` checked 
only the leaf's `IsNull`. Could `bind` keep the plain leaf check when 
`len(chain) == 1`?



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