This is an automated email from the ASF dual-hosted git repository.

zeroshade pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git


The following commit(s) were added to refs/heads/main by this push:
     new 6ef2d55c2 fix(table): update the table's name mapping on schema 
changes (#2646)
6ef2d55c2 is described below

commit 6ef2d55c228ae8d77ffd17146a6eb99cbb836dce
Author: Shivam Sharma <[email protected]>
AuthorDate: Mon Nov 23 23:31:19 2026 +0530

    fix(table): update the table's name mapping on schema changes (#2646)
    
    * fix(table): update the table's name mapping on schema changes
    
    UpdateSchema only updated schema.name-mapping.default when the caller
    passed a mapping with WithNameMapping, which nothing in the repo does.
    After AddColumn or RenameColumn the property still described the old
    schema, so files without field IDs could not be resolved for the new or
    renamed column. AddDataFilesByPath sets the mapping on first use, and a
    later file carrying an added column failed with "missing field_id".
    
    When no mapping is passed, BuildUpdates now updates the table's own
    mapping if it has one, as Java's SchemaUpdate and PyIceberg's
    UpdateSchema do. Tables without the property are left unchanged, and an
    explicit WithNameMapping still takes precedence.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Shivam Sharma 
<[email protected]>
    
    * fix(table): keep an empty name mapping valid on schema updates
    
    UpdateNameMapping returns nil when no mapping entry keeps a name, as for
    [] or entries with empty names, which the spec allows. A rename or
    delete then wrote null to schema.name-mapping.default, and scans and
    add-files rejected the property as invalid. Write [] instead.
    
    Move the name mapping tests into update_schema_test.go, and add a
    compatibility note: schema updates now rewrite the table's name mapping,
    so a new column that reuses a name freed by DeleteColumn or RenameColumn
    maps to that name in older files without field IDs.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    Signed-off-by: Shivam Sharma 
<[email protected]>
    
    * docs(table): say why an unparsable name mapping is left alone
    
    The schema change goes ahead and keeps the stored value, as Java does.
    
    Co-Authored-By: Claude Opus 5.5 <[email protected]>
    
    ---------
    
    Signed-off-by: Shivam Sharma 
<[email protected]>
    Co-authored-by: Claude Opus 5.5 <[email protected]>
---
 table/update_schema.go      |  22 +++++-
 table/update_schema_test.go | 187 ++++++++++++++++++++++++++++++++++++++++++++
 website/src/releases.md     |   1 +
 3 files changed, 208 insertions(+), 2 deletions(-)

diff --git a/table/update_schema.go b/table/update_schema.go
index bbf07be3a..6c15bd00d 100644
--- a/table/update_schema.go
+++ b/table/update_schema.go
@@ -115,6 +115,8 @@ type UpdateSchemaOption func(*UpdateSchema)
 
 // WithNameMapping configures the UpdateSchema to use the provided name mapping
 // for tracking field name changes and ensuring consistency during schema 
evolution.
+// Without it, the table's schema.name-mapping.default property is updated when
+// the table has one.
 func WithNameMapping(nameMapping iceberg.NameMapping) UpdateSchemaOption {
        return func(u *UpdateSchema) {
                u.nameMapping = nameMapping
@@ -1129,15 +1131,31 @@ func (u *UpdateSchema) BuildUpdates() ([]Update, 
[]Requirement, error) {
                        )
                }
 
-               if u.nameMapping != nil {
+               // Keep the table's name mapping in step with the schema, as 
Java's
+               // SchemaUpdate and PyIceberg's UpdateSchema do. Otherwise 
files without
+               // field IDs cannot be resolved for added or renamed columns.
+               nameMapping := u.nameMapping
+               if nameMapping == nil {
+                       // NameMapping returns nil when the property is unset 
or can't be
+                       // parsed. Leaving an unparsable value as it is, rather 
than failing
+                       // the schema change, is deliberate: Java keeps it too.
+                       nameMapping = meta.NameMapping()
+               }
+               if nameMapping != nil {
                        updatesMap := make(map[int]iceberg.NestedField)
                        for _, upds := range u.updates {
                                maps.Copy(updatesMap, upds)
                        }
-                       updatedNameMapping, err := 
iceberg.UpdateNameMapping(u.nameMapping, updatesMap, u.adds)
+                       updatedNameMapping, err := 
iceberg.UpdateNameMapping(nameMapping, updatesMap, u.adds)
                        if err != nil {
                                return nil, nil, err
                        }
+                       // UpdateNameMapping returns nil when no entry keeps a 
name, as
+                       // for [] or entries with empty names. Write [] rather 
than null,
+                       // which would make the property invalid for scans and 
add-files.
+                       if updatedNameMapping == nil {
+                               updatedNameMapping = iceberg.NameMapping{}
+                       }
                        mappingJSON, err := json.Marshal(updatedNameMapping)
                        if err != nil {
                                return nil, nil, err
diff --git a/table/update_schema_test.go b/table/update_schema_test.go
index 85cdfd132..93ace019e 100644
--- a/table/update_schema_test.go
+++ b/table/update_schema_test.go
@@ -18,11 +18,18 @@
 package table
 
 import (
+       "context"
        "encoding/json"
+       "path/filepath"
        "strings"
        "testing"
 
+       "github.com/apache/arrow-go/v18/arrow"
+       "github.com/apache/arrow-go/v18/arrow/array"
+       "github.com/apache/arrow-go/v18/arrow/memory"
+       "github.com/apache/arrow-go/v18/parquet/pqarrow"
        "github.com/apache/iceberg-go"
+       iceio "github.com/apache/iceberg-go/io"
        "github.com/stretchr/testify/assert"
        "github.com/stretchr/testify/require"
 )
@@ -2795,3 +2802,183 @@ func TestRenameColumnDoesNotMutatePath(t *testing.T) {
        require.True(t, ok)
        assert.Equal(t, "the town", f.Doc)
 }
+
+func newNameMappingTestTable(t *testing.T, mapping string) (*Table, string) {
+       t.Helper()
+
+       dir := filepath.ToSlash(t.TempDir())
+       schema := iceberg.NewSchema(0,
+               iceberg.NestedField{ID: 1, Name: "id", Type: 
iceberg.PrimitiveTypes.Int32, Required: true},
+               iceberg.NestedField{ID: 2, Name: "data", Type: 
iceberg.PrimitiveTypes.String},
+       )
+       props := iceberg.Properties{}
+       if mapping != "" {
+               props[DefaultNameMappingKey] = mapping
+       }
+       meta, err := NewMetadata(schema, iceberg.UnpartitionedSpec, 
UnsortedSortOrder, dir, props)
+       require.NoError(t, err)
+
+       tbl := New(Identifier{"default", "name_mapping"}, meta, 
dir+"/metadata/00000.json",
+               func(context.Context) (iceio.IO, error) { return 
iceio.LocalFS{}, nil },
+               &countingCatalog{metadata: meta},
+       )
+
+       return tbl, dir
+}
+
+func mappedNames(mapping iceberg.NameMapping, id int) []string {
+       var names []string
+       var visit func([]iceberg.MappedField)
+       visit = func(fields []iceberg.MappedField) {
+               for _, field := range fields {
+                       if field.FieldID != nil && *field.FieldID == id {
+                               names = append(names, field.Names...)
+                       }
+                       visit(field.Fields)
+               }
+       }
+       visit(mapping)
+
+       return names
+}
+
+// A schema update must keep the table's name mapping in step with the schema,
+// as Java's SchemaUpdate and PyIceberg's UpdateSchema do, or files without
+// field IDs cannot be read for added or renamed columns.
+func TestUpdateSchemaUpdatesTableNameMapping(t *testing.T) {
+       ctx := context.Background()
+       tbl, _ := newNameMappingTestTable(t,
+               
`[{"field-id":1,"names":["id"]},{"field-id":2,"names":["data"]}]`)
+
+       txn := tbl.NewTransaction()
+       require.NoError(t, txn.UpdateSchema(true, false).
+               AddColumn([]string{"category"}, iceberg.PrimitiveTypes.String, 
"", false, nil).
+               RenameColumn([]string{"data"}, "payload").
+               Commit())
+       tbl, err := txn.Commit(ctx)
+       require.NoError(t, err)
+
+       mapping := tbl.Metadata().NameMapping()
+       require.NotNil(t, mapping)
+       assert.Equal(t, []string{"id"}, mappedNames(mapping, 1))
+       assert.Equal(t, []string{"data", "payload"}, mappedNames(mapping, 2))
+       assert.Equal(t, []string{"category"}, mappedNames(mapping, 3))
+}
+
+// Without a name mapping property the update must not add one.
+func TestUpdateSchemaWithoutNameMappingLeavesPropertyUnset(t *testing.T) {
+       ctx := context.Background()
+       tbl, _ := newNameMappingTestTable(t, "")
+
+       txn := tbl.NewTransaction()
+       require.NoError(t, txn.UpdateSchema(true, false).
+               AddColumn([]string{"category"}, iceberg.PrimitiveTypes.String, 
"", false, nil).
+               Commit())
+       tbl, err := txn.Commit(ctx)
+       require.NoError(t, err)
+
+       assert.NotContains(t, tbl.Metadata().Properties(), 
DefaultNameMappingKey)
+}
+
+// A mapping with no named entries is valid. A rename or delete must write it
+// back as [] rather than null, which scans and add-files reject.
+func TestUpdateSchemaKeepsEmptyNameMappingValid(t *testing.T) {
+       rename := func(u *UpdateSchema) *UpdateSchema { return 
u.RenameColumn([]string{"data"}, "payload") }
+       deleteData := func(u *UpdateSchema) *UpdateSchema { return 
u.DeleteColumn([]string{"data"}) }
+
+       tests := []struct {
+               name    string
+               mapping string
+               update  func(*UpdateSchema) *UpdateSchema
+       }{
+               {"empty mapping rename", `[]`, rename},
+               {"empty mapping delete", `[]`, deleteData},
+               {"empty names rename", `[{"field-id":1,"names":[]}]`, rename},
+               {"empty names delete", 
`[{"field-id":1,"names":[]},{"field-id":2,"names":[]}]`, deleteData},
+       }
+
+       for _, tt := range tests {
+               t.Run(tt.name, func(t *testing.T) {
+                       tbl, _ := newNameMappingTestTable(t, tt.mapping)
+
+                       txn := tbl.NewTransaction()
+                       require.NoError(t, tt.update(txn.UpdateSchema(true, 
false)).Commit())
+                       tbl, err := txn.Commit(context.Background())
+                       require.NoError(t, err)
+
+                       props := tbl.Metadata().Properties()
+                       assert.JSONEq(t, `[]`, props[DefaultNameMappingKey])
+                       require.NoError(t, validateNameMappingProperty(props, 
tbl.Metadata().NameMapping()))
+               })
+       }
+}
+
+// End to end: AddDataFilesByPath sets the name mapping, a column is added, and
+// a later file without field IDs that carries the new column is added. Adding
+// that file must succeed and the scan must read the new column from it.
+func TestAddFilesAfterAddColumnReadsNewColumnByName(t *testing.T) {
+       ctx := context.Background()
+       tbl, dir := newNameMappingTestTable(t, "")
+       fs := iceio.LocalFS{}
+
+       writeParquet := func(path string, fields []arrow.Field, cols 
...arrow.Array) {
+               sc := arrow.NewSchema(fields, nil)
+               rec := array.NewRecordBatch(sc, cols, int64(cols[0].Len()))
+               defer rec.Release()
+               arrTbl := array.NewTableFromRecords(sc, 
[]arrow.RecordBatch{rec})
+               defer arrTbl.Release()
+
+               fo, err := fs.Create(ctx, path)
+               require.NoError(t, err)
+               require.NoError(t, pqarrow.WriteTable(arrTbl, fo, 
arrTbl.NumRows(), nil, pqarrow.DefaultWriterProps()))
+       }
+       int32s := func(vals ...int32) arrow.Array {
+               b := array.NewInt32Builder(memory.DefaultAllocator)
+               defer b.Release()
+               b.AppendValues(vals, nil)
+
+               return b.NewArray()
+       }
+       strs := func(vals ...string) arrow.Array {
+               b := array.NewStringBuilder(memory.DefaultAllocator)
+               defer b.Release()
+               b.AppendValues(vals, nil)
+
+               return b.NewArray()
+       }
+
+       idField := arrow.Field{Name: "id", Type: arrow.PrimitiveTypes.Int32}
+       dataField := arrow.Field{Name: "data", Type: arrow.BinaryTypes.String, 
Nullable: true}
+       categoryField := arrow.Field{Name: "category", Type: 
arrow.BinaryTypes.String, Nullable: true}
+
+       first := dir + "/data/first.parquet"
+       writeParquet(first, []arrow.Field{idField, dataField}, int32s(1), 
strs("a"))
+       txn := tbl.NewTransaction()
+       require.NoError(t, txn.AddDataFilesByPath(ctx, []string{first}, nil, 
false))
+       tbl, err := txn.Commit(ctx)
+       require.NoError(t, err)
+       require.Contains(t, tbl.Metadata().Properties(), DefaultNameMappingKey)
+
+       txn = tbl.NewTransaction()
+       require.NoError(t, txn.UpdateSchema(true, false).
+               AddColumn([]string{"category"}, iceberg.PrimitiveTypes.String, 
"", false, nil).
+               Commit())
+       tbl, err = txn.Commit(ctx)
+       require.NoError(t, err)
+
+       second := dir + "/data/second.parquet"
+       writeParquet(second, []arrow.Field{idField, dataField, categoryField}, 
int32s(2), strs("b"), strs("books"))
+       txn = tbl.NewTransaction()
+       require.NoError(t, txn.AddDataFilesByPath(ctx, []string{second}, nil, 
false))
+       tbl, err = txn.Commit(ctx)
+       require.NoError(t, err)
+
+       result, err := 
tbl.Scan(WithRowFilter(iceberg.EqualTo(iceberg.Reference("id"), 
int32(2)))).ToArrowTable(ctx)
+       require.NoError(t, err)
+       defer result.Release()
+
+       require.EqualValues(t, 1, result.NumRows())
+       category := 
result.Column(result.Schema().FieldIndices("category")[0]).Data().Chunk(0).(*array.String)
+       require.False(t, category.IsNull(0), "category was read as null")
+       assert.Equal(t, "books", category.Value(0))
+}
diff --git a/website/src/releases.md b/website/src/releases.md
index 898869b6e..5831f93a6 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -65,6 +65,7 @@ Per-release notes (highlights, breaking changes, 
contributors) are published on
 - **Table history logs reject missing or null required fields.** Loading table 
metadata now fails with `table.ErrInvalidMetadata` if a `snapshot-log` entry 
omits or sets `snapshot-id` or `timestamp-ms` to `null`, or a `metadata-log` 
entry omits or sets `metadata-file` or `timestamp-ms` to `null`. Older 
iceberg-go releases silently accepted omitted or null fields as zero values, 
but Java Iceberg already rejects such metadata. Explicit zero values remain 
valid. Repair affected metadata thr [...]
 
 - **`UpdateSchema` rejects deleting an identifier field.** `DeleteColumn` on 
an identifier column used to succeed and quietly drop the column from the 
table's identifier fields. Now `Apply` (and `Commit`) fails with `cannot delete 
identifier field …`, as in Java. Deleting a struct that contains one already 
failed, and now reports `cannot delete field … as it will delete nested 
identifier field …`. To delete the column anyway, also call 
`SetIdentifierField` with the identifier fields the  [...]
+- **Schema updates rewrite the table's name mapping.** When a table has 
`schema.name-mapping.default`, every `UpdateSchema` commit now updates it, as 
in Java and PyIceberg; before, it changed only when `WithNameMapping` was 
passed. Added columns are mapped by name and renamed columns keep their old 
names, so data files without field IDs resolve them. If a new column reuses a 
name freed by `DeleteColumn` or `RenameColumn`, that name now maps to the new 
column: in older files without field [...]
 - **Schema JSON defaults preserve integer precision.** `long` defaults now 
decode as `int64` instead of `float64`; non-integral, non-numeric, or 
out-of-range values now fail to parse. Numeric literals inside object and list 
defaults decode as `json.Number` rather than `float64`.
 - **REST mutation keys can enable transport replay.** Namespace, table, view, 
transaction and scan-cancellation mutations listed in the [REST catalog 
documentation](./configuration.md) now carry fresh UUIDv7 `Idempotency-Key` 
headers when `GET /v1/config` returns a non-null `idempotency-key-lifetime`. 
Go's HTTP transport may replay certain failed requests on reused connections 
with the same key; the advertised lifetime is not yet enforced. Scan plan and 
task key handling is unchanged. Wh [...]
 - **`StructType.Fields()` returns a copy.** Changing the returned slice no 
longer changes the struct, matching `ListType.Fields()` and `MapType.Fields()`. 
Build a new type with `NewStructType` instead. `NumFields()` and `Field(i)` 
read fields without copying, and `NewListType` and `NewMapType` are the 
constructors for the other nested types. The exported fields are unchanged for 
now; they become unexported before v1.0.0 (see 
[#2062](https://github.com/apache/iceberg-go/issues/2062)).

Reply via email to