zeroshade commented on code in PR #1607:
URL: https://github.com/apache/iceberg-go/pull/1607#discussion_r3935764418


##########
table/variant_residual.go:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+package table
+
+import (
+       "context"
+       "fmt"
+       "log/slog"
+       "strconv"
+       "strings"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/compute"
+       "github.com/apache/arrow-go/v18/arrow/extensions"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/iceberg-go"
+       "github.com/google/uuid"
+)
+
+// augmentSchemaWithExtracts returns fileSchema plus one primitive column per 
variant extract term.
+func augmentSchemaWithExtracts(fileSchema *iceberg.Schema, cols 
[]iceberg.VariantExtractColumn) *iceberg.Schema {
+       fields := fileSchema.Fields()
+       for _, c := range cols {
+               fields = append(fields, iceberg.NestedField{
+                       ID:   c.FieldID,
+                       Name: c.Name,
+                       Type: c.Term.Type().(iceberg.PrimitiveType),
+               })
+       }
+
+       return iceberg.NewSchemaWithIdentifiers(fileSchema.ID, 
fileSchema.IdentifierFieldIDs, fields...)
+}
+
+// buildExtractColumn materializes one variant extract term into a typed Arrow 
array over rec.
+func buildExtractColumn(col iceberg.VariantExtractColumn, rec 
arrow.RecordBatch, mem memory.Allocator) (arrow.Array, arrow.Field, error) {
+       typ := col.Term.Type().(iceberg.PrimitiveType)
+       dt, err := TypeToArrowType(typ, false, false)
+       if err != nil {
+               return nil, arrow.Field{}, err
+       }
+
+       bldr := array.NewBuilder(mem, dt)
+       defer bldr.Release()
+
+       n := int(rec.NumRows())
+       varName := col.Term.Ref().Field().Name
+       arr := resolveVariantSource(rec, col.Term.Ref().Field().ID, 
col.SourcePath)
+       if arr == nil {
+               return nil, arrow.Field{}, fmt.Errorf("%w: variant extract 
column %q not found in file", iceberg.ErrInvalidArgument, varName)
+       }
+       varr, ok := arr.(*extensions.VariantArray)
+       if !ok {
+               return nil, arrow.Field{}, fmt.Errorf("%w: variant extract 
column %q is not a VariantArray (got %T)", iceberg.ErrInvalidArgument, varName, 
arr)
+       }
+
+       for i := range n {
+               if varr.IsNull(i) {
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               v, verr := varr.Value(i)
+               if verr != nil {
+                       slog.Warn("variant extract: skipping undecodable 
variant value", "column", varName, "row", i, "err", verr)
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               lit, ok := col.Term.ExtractValue(v)
+               if !ok {
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               if aerr := appendExtractLiteral(bldr, lit); aerr != nil {
+                       return nil, arrow.Field{}, aerr
+               }
+       }
+
+       field := arrow.Field{
+               Name:     col.Name,
+               Type:     dt,
+               Nullable: true,
+               Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, 
[]string{strconv.Itoa(col.FieldID)}),
+       }
+
+       return bldr.NewArray(), field, nil
+}
+
+// resolveVariantSource locates the extract's source array by field id, 
descending
+// nested structs; it falls back to the file-schema path when field ids are 
absent.
+func resolveVariantSource(rec arrow.RecordBatch, fieldID int, sourcePath 
string) arrow.Array {
+       for i, f := range rec.Schema().Fields() {
+               if a := descendByFieldID(f, rec.Column(i), fieldID); a != nil {
+                       return a
+               }
+       }
+       if sourcePath == "" {
+               return nil
+       }
+
+       return descendByPath(rec.Schema(), rec.Columns(), 
strings.Split(sourcePath, "."))
+}
+
+func descendByFieldID(f arrow.Field, col arrow.Array, fieldID int) arrow.Array 
{
+       if v, ok := f.Metadata.GetValue(ArrowParquetFieldIDKey); ok {
+               if id, err := strconv.Atoi(v); err == nil && id == fieldID {
+                       return col
+               }

Review Comment:
   **minor** — Nested field-id descent is not pinned by any test and appears 
redundant
   
   Deleting the entire struct-descent loop in descendByFieldID leaves the full 
table package green, including TestBuildExtractColumnNested whose assertion 
message claims 'nested variant resolved by descending the struct' but which 
actually resolves via the descendByPath fallback. Because fileSchema is derived 
from the same pruned Arrow schema the record batches carry, the path walk 
always aligns, so the field-id recursion has no exercised code path. Either add 
a test that only the field-id descent can satisfy (field ids present, path 
unresolvable) or drop the recursion and keep descendByPath.



##########
visitors.go:
##########
@@ -802,54 +884,79 @@ const sanitizedLiteralMask = "(redacted)"
 // predicates (IN / NOT IN) keep their arity so the operation is not
 // misrepresented, but the members are masked.
 func SanitizeExpression(expr BooleanExpression) (BooleanExpression, error) {
-       return VisitExpr(expr, sanitizeVisitor{})
+       res, err := VisitExpr(expr, sanitizeVisitor{})
+       if err != nil {
+               return nil, err
+       }
+
+       return res.expr, nil
+}
+
+// sanitizedResult is the masked expression plus whether its subtree held a 
non-serializable term.
+type sanitizedResult struct {
+       expr              BooleanExpression
+       hasUnserializable bool

Review Comment:
   **nit** — NOT over a mixed subtree discards the serializable conjuncts from 
the ScanReport filter
   
   VisitNot collapses the whole subtree to AlwaysTrue whenever any descendant 
was unserializable, so NOT(AND(extract=5, x<10)) reports AlwaysTrue and the 
surviving x<10 never reaches ScanReport.Filter. The direction is safe 
(over-broad, never AlwaysFalse) and matches the bbox convention, but the 
emitted report can under-report the executed filter. Worth a one-line comment 
on the tradeoff, or push the collapse down to the offending leaf and negate the 
rest.



##########
table/variant_residual.go:
##########
@@ -0,0 +1,316 @@
+// 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.
+
+package table
+
+import (
+       "context"
+       "fmt"
+       "log/slog"
+       "strconv"
+       "strings"
+
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/compute"
+       "github.com/apache/arrow-go/v18/arrow/extensions"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/iceberg-go"
+       "github.com/google/uuid"
+)
+
+// augmentSchemaWithExtracts returns fileSchema plus one primitive column per 
variant extract term.
+func augmentSchemaWithExtracts(fileSchema *iceberg.Schema, cols 
[]iceberg.VariantExtractColumn) *iceberg.Schema {
+       fields := fileSchema.Fields()
+       for _, c := range cols {
+               fields = append(fields, iceberg.NestedField{
+                       ID:   c.FieldID,
+                       Name: c.Name,
+                       Type: c.Term.Type().(iceberg.PrimitiveType),
+               })
+       }
+
+       return iceberg.NewSchemaWithIdentifiers(fileSchema.ID, 
fileSchema.IdentifierFieldIDs, fields...)
+}
+
+// buildExtractColumn materializes one variant extract term into a typed Arrow 
array over rec.
+func buildExtractColumn(col iceberg.VariantExtractColumn, rec 
arrow.RecordBatch, mem memory.Allocator) (arrow.Array, arrow.Field, error) {
+       typ := col.Term.Type().(iceberg.PrimitiveType)
+       dt, err := TypeToArrowType(typ, false, false)
+       if err != nil {
+               return nil, arrow.Field{}, err
+       }
+
+       bldr := array.NewBuilder(mem, dt)
+       defer bldr.Release()
+
+       n := int(rec.NumRows())
+       varName := col.Term.Ref().Field().Name
+       arr := resolveVariantSource(rec, col.Term.Ref().Field().ID, 
col.SourcePath)
+       if arr == nil {
+               return nil, arrow.Field{}, fmt.Errorf("%w: variant extract 
column %q not found in file", iceberg.ErrInvalidArgument, varName)
+       }
+       varr, ok := arr.(*extensions.VariantArray)
+       if !ok {
+               return nil, arrow.Field{}, fmt.Errorf("%w: variant extract 
column %q is not a VariantArray (got %T)", iceberg.ErrInvalidArgument, varName, 
arr)
+       }
+
+       for i := range n {
+               if varr.IsNull(i) {
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               v, verr := varr.Value(i)
+               if verr != nil {
+                       slog.Warn("variant extract: skipping undecodable 
variant value", "column", varName, "row", i, "err", verr)
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               lit, ok := col.Term.ExtractValue(v)
+               if !ok {
+                       bldr.AppendNull()
+
+                       continue
+               }
+
+               if aerr := appendExtractLiteral(bldr, lit); aerr != nil {
+                       return nil, arrow.Field{}, aerr
+               }
+       }
+
+       field := arrow.Field{
+               Name:     col.Name,
+               Type:     dt,
+               Nullable: true,
+               Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, 
[]string{strconv.Itoa(col.FieldID)}),
+       }
+
+       return bldr.NewArray(), field, nil
+}
+
+// resolveVariantSource locates the extract's source array by field id, 
descending
+// nested structs; it falls back to the file-schema path when field ids are 
absent.
+func resolveVariantSource(rec arrow.RecordBatch, fieldID int, sourcePath 
string) arrow.Array {
+       for i, f := range rec.Schema().Fields() {
+               if a := descendByFieldID(f, rec.Column(i), fieldID); a != nil {
+                       return a
+               }
+       }
+       if sourcePath == "" {
+               return nil
+       }

Review Comment:
   **minor** — strings.Split on '.' misresolves Variant columns whose Iceberg 
name contains a dot
   
   resolveVariantSource re-splits the flattened column name returned by 
FindColumnName, so a legal Iceberg column literally named 'a.b' is looked up as 
top-level 'a' then child 'b'. On a name-mapped (field-id-less) file this aborts 
the scan. Resolve by walking the Iceberg schema's nested field structure 
(carrying the path segments through from FindColumnName) instead of 
re-splitting the flattened name.



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