twuebi commented on code in PR #596:
URL: https://github.com/apache/iceberg-go/pull/596#discussion_r2416490809


##########
table/update_schema.go:
##########
@@ -0,0 +1,884 @@
+// 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 (
+       "errors"
+       "fmt"
+       "maps"
+       "slices"
+       "strings"
+
+       "github.com/apache/iceberg-go"
+)
+
+const TableRootID = -1
+
+type MoveOp string
+
+const (
+       MoveOpFirst  MoveOp = "first"
+       MoveOpBefore MoveOp = "before"
+       MoveOpAfter  MoveOp = "after"
+)
+
+type move struct {
+       FieldID    int
+       RelativeTo int
+       Op         MoveOp
+}
+
+type UpdateSchema struct {
+       txn          *Transaction
+       schema       *iceberg.Schema
+       lastColumnID int
+
+       deletes map[int]struct{}
+       updates map[int]map[int]iceberg.NestedField
+       adds    map[int][]iceberg.NestedField
+       moves   map[int][]move
+
+       identifierFieldNames map[string]struct{}
+       parentID             map[int]int
+
+       addedNameToID            map[string]int
+       allowIncompatibleChanges bool
+       caseSensitive            bool
+       nameMapping              iceberg.NameMapping
+       ops                      []func() error
+}
+
+type UpdateSchemaOption func(*UpdateSchema)
+
+func WithNameMapping(nameMapping iceberg.NameMapping) UpdateSchemaOption {
+       return func(u *UpdateSchema) {
+               u.nameMapping = nameMapping
+       }
+}
+
+func NewUpdateSchema(txn *Transaction, caseSensitive bool, 
allowIncompatibleChanges bool, opts ...UpdateSchemaOption) *UpdateSchema {
+       u := &UpdateSchema{
+               txn:          txn,
+               schema:       nil,
+               lastColumnID: txn.meta.CurrentSchema().HighestFieldID(),
+
+               deletes: make(map[int]struct{}),
+               updates: make(map[int]map[int]iceberg.NestedField),
+               adds:    make(map[int][]iceberg.NestedField),
+               moves:   make(map[int][]move),
+
+               identifierFieldNames: nil,
+               parentID:             make(map[int]int),
+
+               addedNameToID:            make(map[string]int),
+               allowIncompatibleChanges: allowIncompatibleChanges,
+               caseSensitive:            caseSensitive,
+               nameMapping:              nil,
+               ops:                      make([]func() error, 0),
+       }
+
+       for _, opt := range opts {
+               opt(u)
+       }
+
+       return u
+}
+
+func (u *UpdateSchema) init() error {
+       if u.txn == nil {
+               return errors.New("transaction is nil")
+       }
+       if u.txn.meta == nil {
+               return errors.New("transaction meta is nil")
+       }
+
+       u.schema = u.txn.meta.CurrentSchema()
+       if u.schema == nil {
+               return errors.New("current schema is nil")
+       }
+
+       if err := u.initIdentifierFieldNames(); err != nil {
+               return err
+       }
+
+       if err := u.initParentID(); err != nil {
+               return err
+       }
+
+       return nil
+}
+
+func (u *UpdateSchema) initIdentifierFieldNames() error {
+       if u.identifierFieldNames != nil {
+               return nil
+       }
+
+       identifierFieldNames := make(map[string]struct{})
+       for _, id := range u.schema.IdentifierFieldIDs {
+               name, ok := u.schema.FindColumnName(id)
+               if !ok {
+                       return fmt.Errorf("identifier field %d not found", id)
+               }
+               identifierFieldNames[name] = struct{}{}
+       }
+
+       u.identifierFieldNames = identifierFieldNames
+
+       return nil
+}
+
+func (u *UpdateSchema) initParentID() error {
+       parents, err := iceberg.IndexParents(u.schema)
+       if err != nil {
+               return err
+       }
+
+       maps.Copy(u.parentID, parents)
+
+       return nil
+}
+
+func (u *UpdateSchema) assignNewColumnID() int {
+       u.lastColumnID++
+
+       return u.lastColumnID
+}
+
+func (u *UpdateSchema) findField(name string) (iceberg.NestedField, bool) {
+       if u.caseSensitive {
+               return u.schema.FindFieldByName(name)
+       } else {
+               return u.schema.FindFieldByNameCaseInsensitive(name)
+       }
+}
+
+func (u *UpdateSchema) isDeleted(fieldID int) bool {
+       _, ok := u.deletes[fieldID]
+
+       return ok
+}
+
+func (u *UpdateSchema) findParentID(fieldID int) int {
+       parentID, ok := u.parentID[fieldID]
+       if !ok {
+               return TableRootID
+       }
+
+       return parentID
+}
+
+func (u *UpdateSchema) AddColumn(path []string, fieldType iceberg.Type, doc 
string, required bool, defaultValue iceberg.Literal) *UpdateSchema {
+       u.ops = append(u.ops, func() error {
+               return u.addColumn(path, fieldType, doc, required, defaultValue)
+       })
+
+       return u
+}
+
+func (u *UpdateSchema) addColumn(path []string, fieldType iceberg.Type, doc 
string, required bool, defaultValue iceberg.Literal) error {
+       if len(path) == 0 {
+               return errors.New("path is empty")
+       }
+
+       fullName := strings.Join(path, ".")
+
+       switch t := fieldType.(type) {
+       case *iceberg.ListType, *iceberg.MapType, *iceberg.StructType:
+               if defaultValue != nil {
+                       return fmt.Errorf("default values are not supported for 
%s", t.String())
+               }
+       case iceberg.PrimitiveType:
+               if required && defaultValue == nil && 
!u.allowIncompatibleChanges {
+                       return fmt.Errorf("required field %s has no default 
value", fullName)
+               }
+               if defaultValue != nil && !defaultValue.Type().Equals(t) {
+                       return fmt.Errorf("default value type mismatch: %s != 
%s", defaultValue.Type(), t)
+               }
+       default:
+               return fmt.Errorf("invalid field type: %T", t)
+       }
+
+       parent := path[:len(path)-1]
+       parentID := TableRootID
+
+       if len(parent) > 0 {
+               parentFullPath := strings.Join(parent, ".")
+               parentField, ok := u.findField(parentFullPath)
+               if !ok {
+                       return fmt.Errorf("parent field not found: %s", 
parentFullPath)
+               }
+
+               switch parentType := parentField.Type.(type) {
+               case *iceberg.ListType:
+                       f := parentType.ElementField()
+                       parentField = f
+               case *iceberg.MapType:
+                       f := parentType.ValueField()
+                       parentField = f
+               }
+
+               if _, ok := parentField.Type.(*iceberg.StructType); !ok {
+                       return fmt.Errorf("cannot add field to non-struct type: 
%s", parentFullPath)
+               }
+
+               parentID = parentField.ID
+       }
+
+       name := path[len(path)-1]
+       for _, add := range u.adds[parentID] {
+               if add.Name == name {
+                       return fmt.Errorf("field already exists in adds: %s", 
fullName)
+               }
+       }
+
+       // support add field with the same name as deleted field and renamed 
field
+       if field, ok := u.findField(fullName); ok {
+               if !u.isDeleted(field.ID) {
+                       for _, upd := range u.updates[parentID] {
+                               if upd.Name == name {
+                                       return fmt.Errorf("field already 
exists: %s", fullName)
+                               }
+                       }
+               }
+       }
+
+       field := iceberg.NestedField{
+               Name:     name,
+               Type:     fieldType,
+               Required: required,
+               Doc:      doc,
+       }
+       if defaultValue != nil {
+               field.InitialDefault = defaultValue.Any()
+               field.WriteDefault = defaultValue.Any()
+       }
+
+       sch, err := iceberg.AssignFreshSchemaIDs(iceberg.NewSchema(0, field), 
u.assignNewColumnID)
+       if err != nil {
+               return fmt.Errorf("failed to assign field id: %w", err)
+       }
+       u.adds[parentID] = append(u.adds[parentID], sch.Field(0))
+       u.addedNameToID[fullName] = sch.Field(0).ID

Review Comment:
   Why are we doing this? We're creating a new schema with a single field that 
we init with ID 0,  just to make sure that field.ID is > lastColumnId? 
   
   Iceberg java simply does this (`org/apache/iceberg/SchemaUpdate.java:164`):
   
   ```java
       // assign new IDs in order
       int newId = assignNewColumnId();
   
       // update tracking for moves
       addedNameToId.put(fullName, newId);
       if (parentId != TABLE_ROOT_ID) {
         idToParent.put(newId, parentId);
       }
   
       Types.NestedField newField =
           Types.NestedField.builder()
               .withName(name)
               .isOptional(isOptional)
               .withId(newId)
               .ofType(TypeUtil.assignFreshIds(type, this::assignNewColumnId))
               .withDoc(doc)
               .withInitialDefault(defaultValue)
               .withWriteDefault(defaultValue)
               .build();
   ```



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