This is an automated email from the ASF dual-hosted git repository.
laskoviymishka 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 b1fa4e35d refactor!: unexport nested type and schema identifier fields
(#2655)
b1fa4e35d is described below
commit b1fa4e35db82be51f5adae831400913acea9a38d
Author: Revanth <[email protected]>
AuthorDate: Wed Nov 25 02:02:08 2026 -0600
refactor!: unexport nested type and schema identifier fields (#2655)
---
catalog/glue/glue_test.go | 2 +-
.../rest/scan_task_schema_history_lookup_test.go | 3 +-
data_file_codec_bench_test.go | 2 +-
data_file_codec_fingerprint_test.go | 8 +-
data_file_codec_test.go | 4 +-
defaults.go | 16 +-
defaults_test.go | 4 +-
manifest.go | 2 +-
metadata_columns.go | 2 +-
name_mapping.go | 30 +--
nested_type_json_internal_test.go | 8 +-
partitions.go | 2 +-
partitions_test.go | 16 --
schema.go | 190 +++++++--------
schema_clone_internal_test.go | 256 +++++++++++++++++++++
schema_column_path_test.go | 10 +-
schema_compatibility.go | 18 +-
schema_conversions.go | 4 +-
schema_conversions_test.go | 18 +-
schema_highest_field_id_bench_test.go | 14 +-
schema_identifier_fields_validation_test.go | 22 +-
schema_name_index_bench_test.go | 2 +-
schema_name_index_internal_test.go | 14 +-
schema_test.go | 250 +++-----------------
table/arrow_filter_plan.go | 16 +-
table/arrow_filter_plan_test.go | 66 +++---
table/arrow_scanner.go | 6 +-
table/changelog_normalization.go | 2 +-
table/equality_delete_reader.go | 2 +-
table/inspect/inspect_test.go | 14 +-
table/internal/parquet_files.go | 6 +-
table/metadata.go | 2 +-
table/metadata_builder_from_base_test.go | 2 -
table/metadata_getters_test.go | 8 +-
table/metadata_internal_test.go | 4 +-
table/reference_tables_test.go | 26 +--
table/scan_planning_remote.go | 14 +-
table/scanner.go | 2 +-
table/scanner_internal_test.go | 2 +-
table/stats_ndv_test.go | 8 +-
table/update_schema.go | 12 +-
table/update_schema_test.go | 70 +++---
table/variant_residual.go | 2 +-
types.go | 138 ++++++-----
types_internal_test.go | 64 ++++++
types_test.go | 126 +++++-----
types_verification_test.go | 8 +-
variant_extract_test.go | 2 +-
view/metadata.go | 2 +-
view/metadata_builder.go | 2 +-
view/metadata_test.go | 27 ++-
website/src/api.md | 2 +-
website/src/releases.md | 9 +-
53 files changed, 854 insertions(+), 687 deletions(-)
diff --git a/catalog/glue/glue_test.go b/catalog/glue/glue_test.go
index fa028083e..173c1d660 100644
--- a/catalog/glue/glue_test.go
+++ b/catalog/glue/glue_test.go
@@ -2243,7 +2243,7 @@ func TestAlterTableIntegration(t *testing.T) {
}
newFields := append(currentSchema.Fields(), addField) // add column
'new_col'
newFields = append(newFields[:1], newFields[2:]...) // drop column
'bar'
- updateColumns :=
table.NewAddSchemaUpdate(iceberg.NewSchemaWithIdentifiers(newSchemaId,
currentSchema.IdentifierFieldIDs, newFields...))
+ updateColumns :=
table.NewAddSchemaUpdate(iceberg.NewSchemaWithIdentifiers(newSchemaId,
currentSchema.IdentifierFieldIDs(), newFields...))
setSchema := table.NewSetCurrentSchemaUpdate(newSchemaId)
_, _, err = ctlg.CommitTable(
diff --git a/catalog/rest/scan_task_schema_history_lookup_test.go
b/catalog/rest/scan_task_schema_history_lookup_test.go
index 79eccc510..64166a7d2 100644
--- a/catalog/rest/scan_task_schema_history_lookup_test.go
+++ b/catalog/rest/scan_task_schema_history_lookup_test.go
@@ -20,7 +20,6 @@ package rest
import (
"encoding/json"
"fmt"
- "slices"
"testing"
"github.com/apache/iceberg-go"
@@ -43,7 +42,7 @@ func cloneDecoderSchemaForTest(schema *iceberg.Schema)
*iceberg.Schema {
}
return iceberg.NewSchemaWithIdentifiers(
- schema.ID, slices.Clone(schema.IdentifierFieldIDs),
schema.Fields()...,
+ schema.ID, schema.IdentifierFieldIDs(), schema.Fields()...,
)
}
diff --git a/data_file_codec_bench_test.go b/data_file_codec_bench_test.go
index c118bc563..6aa5e9475 100644
--- a/data_file_codec_bench_test.go
+++ b/data_file_codec_bench_test.go
@@ -31,7 +31,7 @@ func BenchmarkDataFileSchemaCache(b *testing.B) {
NestedField{ID: 2, Name: "category", Type: StringType{}},
NestedField{ID: 3, Name: "ts", Type: TimestampType{}},
NestedField{ID: 4, Name: "price", Type: MustDecimalTypeOf(10,
2)},
- NestedField{ID: 5, Name: "nested", Type: &StructType{FieldList:
[]NestedField{
+ NestedField{ID: 5, Name: "nested", Type: &StructType{fields:
[]NestedField{
{ID: 6, Name: "value", Type: StringType{}},
}}},
)
diff --git a/data_file_codec_fingerprint_test.go
b/data_file_codec_fingerprint_test.go
index 40603fe8a..08b79b1b9 100644
--- a/data_file_codec_fingerprint_test.go
+++ b/data_file_codec_fingerprint_test.go
@@ -53,16 +53,16 @@ func TestPartitionTypeFingerprintMatchesAvroConversion(t
*testing.T) {
MustDecimalTypeOf(10, 2),
MustDecimalTypeOf(11, 2),
MustDecimalTypeOf(10, 3),
- &StructType{FieldList: []NestedField{{ID: 2, Name: "child",
Type: StringType{}}}},
- &ListType{ElementID: 2, Element: StringType{}},
- &MapType{KeyID: 2, KeyType: StringType{}, ValueID: 3,
ValueType: Int64Type{}},
+ &StructType{fields: []NestedField{{ID: 2, Name: "child", Type:
StringType{}}}},
+ &ListType{elementID: 2, element: StringType{}},
+ &MapType{keyID: 2, keyType: StringType{}, valueID: 3,
valueType: Int64Type{}},
}
shapes := make(map[string]string, len(types))
for _, typ := range types {
t.Run(typ.String(), func(t *testing.T) {
var key strings.Builder
fingerprintErr := writePartitionTypeFingerprint(&key,
typ)
- partition, avroErr :=
partitionTypeToAvroSchema(&StructType{FieldList: []NestedField{
+ partition, avroErr :=
partitionTypeToAvroSchema(&StructType{fields: []NestedField{
{ID: 1000, Name: "partition", Type: typ},
}})
if avroErr != nil {
diff --git a/data_file_codec_test.go b/data_file_codec_test.go
index 013bd58fb..402f7ea6f 100644
--- a/data_file_codec_test.go
+++ b/data_file_codec_test.go
@@ -606,8 +606,8 @@ func
TestManifestEntrySchemaForRejectsInvalidTypesAfterCacheHit(t *testing.T) {
for _, typ := range []Type{
unsupportedCodecPartitionType{},
VariantType{},
- &StructType{}, &ListType{ElementID: 2, Element: Int64Type{}},
- &MapType{KeyID: 2, KeyType: StringType{}, ValueID: 3,
ValueType: Int64Type{}},
+ &StructType{}, &ListType{elementID: 2, element: Int64Type{}},
+ &MapType{keyID: 2, keyType: StringType{}, valueID: 3,
valueType: Int64Type{}},
} {
schema := NewSchema(1, NestedField{ID: 1, Name: "source", Type:
typ})
_, wantErr :=
partitionTypeToAvroSchema(spec.PartitionType(schema))
diff --git a/defaults.go b/defaults.go
index 1c655e50a..7f1765a90 100644
--- a/defaults.go
+++ b/defaults.go
@@ -120,39 +120,39 @@ func normalizeTypeDefaults(typ Type) (Type, bool) {
if typ == nil {
return nil, false
}
- fields, ok := normalizeDefaults(typ.FieldList)
+ fields, ok := normalizeDefaults(typ.fields)
if !ok {
return nil, false
}
- return &StructType{FieldList: fields}, true
+ return &StructType{fields: fields}, true
case *ListType:
if typ == nil {
return nil, false
}
- elem, ok := normalizeTypeDefaults(typ.Element)
+ elem, ok := normalizeTypeDefaults(typ.element)
if !ok {
return nil, false
}
cloned := *typ
- cloned.Element = elem
+ cloned.element = elem
return &cloned, true
case *MapType:
if typ == nil {
return nil, false
}
- key, keyOK := normalizeTypeDefaults(typ.KeyType)
- value, valueOK := normalizeTypeDefaults(typ.ValueType)
+ key, keyOK := normalizeTypeDefaults(typ.keyType)
+ value, valueOK := normalizeTypeDefaults(typ.valueType)
if !keyOK && !valueOK {
return nil, false
}
cloned := *typ
if keyOK {
- cloned.KeyType = key
+ cloned.keyType = key
}
if valueOK {
- cloned.ValueType = value
+ cloned.valueType = value
}
return &cloned, true
diff --git a/defaults_test.go b/defaults_test.go
index 7ccdb382f..0d405ce8f 100644
--- a/defaults_test.go
+++ b/defaults_test.go
@@ -142,7 +142,7 @@ func
TestNewSchemaNormalizesNestedByteDefaultsWithoutModifyingCaller(t *testing.
assert.Equal(t, "03", top.WriteDefault)
assert.Equal(t, []byte{1, 2}, inner.Field(0).InitialDefault)
- assert.Same(t, list, mapType.ValueType)
- assert.Same(t, inner, list.Element)
+ assert.Same(t, list, mapType.ValueType())
+ assert.Same(t, inner, list.Element())
assert.Equal(t, []byte{3}, fields[1].WriteDefault)
}
diff --git a/manifest.go b/manifest.go
index 453471fd8..1e2193745 100644
--- a/manifest.go
+++ b/manifest.go
@@ -1732,7 +1732,7 @@ type partitionSummaryStats struct {
}
func newPartitionSummaryStats(spec PartitionSpec, schema *Schema)
(*partitionSummaryStats, error) {
- fields := spec.PartitionType(schema).FieldList
+ fields := spec.PartitionType(schema).fields
stats := make([]fieldStats, len(fields))
var err error
for i, field := range fields {
diff --git a/metadata_columns.go b/metadata_columns.go
index 4459882e4..07ce56fed 100644
--- a/metadata_columns.go
+++ b/metadata_columns.go
@@ -129,7 +129,7 @@ func SchemaWithRowLineageColumns(s *Schema, rowID,
lastUpdatedSeq bool) *Schema
fields = append(fields, LastUpdatedSequenceNumber())
}
- return NewSchemaWithIdentifiers(s.ID, s.IdentifierFieldIDs, fields...)
+ return NewSchemaWithIdentifiers(s.ID, s.identifierFieldIDs, fields...)
}
// SchemaWithRowID returns a new schema with only the _row_id metadata column
diff --git a/name_mapping.go b/name_mapping.go
index 5a31dba5e..28e5e2eff 100644
--- a/name_mapping.go
+++ b/name_mapping.go
@@ -449,7 +449,7 @@ func (n *nameMapProjectVisitor) Schema(_ *Schema, _
*MappedField, structResult N
func (n *nameMapProjectVisitor) Struct(_ StructType, _ *MappedField,
fieldResults []NestedField) NestedField {
return NestedField{
- Type: &StructType{FieldList: fieldResults},
+ Type: &StructType{fields: fieldResults},
}
}
@@ -489,9 +489,9 @@ func (n *nameMapProjectVisitor) List(lt ListType,
listPartner *MappedField, elem
return NestedField{
Type: &ListType{
- ElementID: elementID,
- Element: elemResult.Type,
- ElementRequired: lt.ElementRequired,
+ elementID: elementID,
+ element: elemResult.Type,
+ elementRequired: lt.elementRequired,
},
}
}
@@ -507,11 +507,11 @@ func (n *nameMapProjectVisitor) Map(m MapType, mapPartner
*MappedField, keyResul
return NestedField{
Type: &MapType{
- KeyID: keyID,
- KeyType: keyResult.Type,
- ValueID: valID,
- ValueType: valResult.Type,
- ValueRequired: m.ValueRequired,
+ keyID: keyID,
+ keyType: keyResult.Type,
+ valueID: valID,
+ valueType: valResult.Type,
+ valueRequired: m.valueRequired,
},
}
}
@@ -552,7 +552,7 @@ func ApplyNameMapping(schemaWithoutIDs *Schema, nameMapping
NameMapping) (*Schem
return nil, err
}
- fields := top.Type.(*StructType).FieldList
+ fields := top.Type.(*StructType).fields
if err := checkDuplicateFieldIDs(nil, fields); err != nil {
return nil, err
}
@@ -567,8 +567,8 @@ func (createMapping) Schema(_ *Schema, result
[]MappedField) []MappedField {
}
func (createMapping) Struct(st StructType, result [][]MappedField)
[]MappedField {
- output := make([]MappedField, len(st.FieldList))
- for i, field := range st.FieldList {
+ output := make([]MappedField, len(st.fields))
+ for i, field := range st.fields {
output[i] = MappedField{
Names: []string{field.Name},
FieldID: &field.ID,
@@ -586,7 +586,7 @@ func (createMapping) Field(_ NestedField, result
[]MappedField) []MappedField {
func (createMapping) List(listType ListType, elemResult []MappedField)
[]MappedField {
return []MappedField{{
Names: []string{"element"},
- FieldID: &listType.ElementID,
+ FieldID: &listType.elementID,
Fields: elemResult,
}}
}
@@ -595,12 +595,12 @@ func (createMapping) Map(mapType MapType, keyResult,
valResult []MappedField) []
return []MappedField{
{
Names: []string{"key"},
- FieldID: &mapType.KeyID,
+ FieldID: &mapType.keyID,
Fields: keyResult,
},
{
Names: []string{"value"},
- FieldID: &mapType.ValueID,
+ FieldID: &mapType.valueID,
Fields: valResult,
},
}
diff --git a/nested_type_json_internal_test.go
b/nested_type_json_internal_test.go
index 30eca8487..45a71385a 100644
--- a/nested_type_json_internal_test.go
+++ b/nested_type_json_internal_test.go
@@ -31,19 +31,19 @@ import (
// field. It walks unexported fields too, so it keeps working after #2062.
func TestNestedTypeJSONRoundTripsEveryField(t *testing.T) {
t.Run("StructType", func(t *testing.T) {
- requireJSONRoundTripsEveryField(t, StructType{FieldList:
[]NestedField{
+ requireJSONRoundTripsEveryField(t, StructType{fields:
[]NestedField{
{ID: 1, Name: "a", Type: PrimitiveTypes.Int32,
Required: true},
}})
})
t.Run("ListType", func(t *testing.T) {
requireJSONRoundTripsEveryField(t, ListType{
- ElementID: 1, Element: PrimitiveTypes.String,
ElementRequired: true,
+ elementID: 1, element: PrimitiveTypes.String,
elementRequired: true,
})
})
t.Run("MapType", func(t *testing.T) {
requireJSONRoundTripsEveryField(t, MapType{
- KeyID: 1, KeyType: PrimitiveTypes.String,
- ValueID: 2, ValueType: PrimitiveTypes.Int32,
ValueRequired: true,
+ keyID: 1, keyType: PrimitiveTypes.String,
+ valueID: 2, valueType: PrimitiveTypes.Int32,
valueRequired: true,
})
})
t.Run("NestedField", func(t *testing.T) {
diff --git a/partitions.go b/partitions.go
index 5ef33618b..7150f843b 100644
--- a/partitions.go
+++ b/partitions.go
@@ -1022,7 +1022,7 @@ func (ps *PartitionSpec) PartitionType(schema *Schema)
*StructType {
}
}
- return &StructType{FieldList: nestedFields}
+ return &StructType{fields: nestedFields}
}
// PartitionToPath produces a proper partition path from the data and schema by
diff --git a/partitions_test.go b/partitions_test.go
index 26dda21bd..5ba1e784c 100644
--- a/partitions_test.go
+++ b/partitions_test.go
@@ -578,22 +578,6 @@ func TestPartitionTypeResolvesEachSchema(t *testing.T) {
}
}
-func TestPartitionTypeReturnsIndependentFields(t *testing.T) {
- schema := iceberg.NewSchema(0, iceberg.NestedField{ID: 1, Name:
"value", Type: iceberg.StringType{}})
- spec := iceberg.NewPartitionSpec(iceberg.PartitionField{
- SourceIDs: []int{1}, FieldID: 1000, Name: "value", Transform:
iceberg.IdentityTransform{},
- })
- first := spec.PartitionType(schema)
- second := spec.PartitionType(schema)
- first.FieldList[0] = iceberg.NestedField{ID: 2000, Name: "changed",
Type: iceberg.Int64Type{}, Required: true}
-
- want := []iceberg.NestedField{{ID: 1000, Name: "value", Type:
iceberg.StringType{}}}
- require.Equal(t, want, second.Fields())
- require.Equal(t, want, spec.PartitionType(schema).Fields())
- require.Equal(t, "value", spec.Field(0).Name)
- require.Equal(t, 1000, spec.Field(0).FieldID)
-}
-
func TestPartitionTypeUnpartitioned(t *testing.T) {
for _, spec := range []iceberg.PartitionSpec{{},
iceberg.NewPartitionSpec()} {
partitionType := spec.PartitionType(nil)
diff --git a/schema.go b/schema.go
index 897abebf5..cd2587db4 100644
--- a/schema.go
+++ b/schema.go
@@ -39,8 +39,9 @@ import (
// rather than exposing the slice directly in order to ensure a schema
// as immutable.
type Schema struct {
- ID int `json:"schema-id"`
- IdentifierFieldIDs []int `json:"identifier-field-ids"`
+ ID int `json:"schema-id"`
+
+ identifierFieldIDs []int
fields []NestedField
@@ -85,10 +86,11 @@ func NewSchema(id int, fields ...NestedField) *Schema {
// lists and maps, are stored as hex strings when given as []byte,
// [BinaryLiteral] or [FixedLiteral], the form they take in metadata JSON.
// Byte slices inside other defaults are left as they are. The provided fields
-// and types are not modified.
+// and types are not modified, and the schema keeps its own copy of
+// identifierIDs.
func NewSchemaWithIdentifiers(id int, identifierIDs []int, fields
...NestedField) *Schema {
fields, _ = normalizeDefaults(fields)
- s := &Schema{ID: id, fields: fields, IdentifierFieldIDs: identifierIDs}
+ s := &Schema{ID: id, fields: fields, identifierFieldIDs:
slices.Clone(identifierIDs)}
s.init()
// Eagerly check for duplicate field IDs, mirroring Java's
Schema.<init>.
@@ -107,7 +109,7 @@ func NewSchemaWithIdentifiers(id int, identifierIDs []int,
fields ...NestedField
// may only be nested in required structs. Callers that construct temporary
// schemas can defer this validation until reading or writing metadata.
func (s *Schema) ValidateIdentifierFields() error {
- if len(s.IdentifierFieldIDs) == 0 {
+ if len(s.identifierFieldIDs) == 0 {
return nil
}
@@ -120,8 +122,8 @@ func (s *Schema) ValidateIdentifierFields() error {
return err
}
- seen := make(map[int]struct{}, len(s.IdentifierFieldIDs))
- for _, id := range s.IdentifierFieldIDs {
+ seen := make(map[int]struct{}, len(s.identifierFieldIDs))
+ for _, id := range s.identifierFieldIDs {
if _, exists := seen[id]; exists {
return fmt.Errorf("%w: duplicate identifier field id
%d", ErrInvalidSchema, id)
}
@@ -196,7 +198,7 @@ func checkFieldIDs(seen map[int]string, fields
[]NestedField, allIDs bool) error
switch t := f.Type.(type) {
case *StructType:
if t != nil {
- if err := checkFieldIDs(seen, t.FieldList,
allIDs); err != nil {
+ if err := checkFieldIDs(seen, t.fields,
allIDs); err != nil {
return err
}
}
@@ -382,12 +384,12 @@ func (s *Schema) Type() string { return "struct" }
// AsStruct returns a Struct with the same fields as the schema which can
// then be used as a Type.
-func (s *Schema) AsStruct() StructType { return StructType{FieldList:
cloneFields(s.fields)} }
+func (s *Schema) AsStruct() StructType { return StructType{fields:
cloneFields(s.fields)} }
// asStructRef returns a read-only view over the schema field slice for
// internal callers that only traverse fields and must avoid clone-on-read
// overhead on hot paths.
-func (s *Schema) asStructRef() StructType { return StructType{FieldList:
s.fields} }
+func (s *Schema) asStructRef() StructType { return StructType{fields:
s.fields} }
func (s *Schema) NumFields() int { return len(s.fields) }
func (s *Schema) Field(i int) NestedField { return cloneField(s.fields[i]) }
@@ -402,6 +404,10 @@ func (s *Schema) Fields() []NestedField { return
cloneFields(s.fields) }
// compatibility guarantees. Use [Schema.Fields] instead.
func (s *Schema) FieldsRef(_ internal.SchemaRef) []NestedField { return
s.fields }
+// IdentifierFieldIDs returns a copy of the IDs of the schema's identifier
+// fields.
+func (s *Schema) IdentifierFieldIDs() []int { return
slices.Clone(s.identifierFieldIDs) }
+
func (s *Schema) FieldIDs() []int {
idx, _ := s.lazyNameToID()
@@ -450,12 +456,12 @@ func (s *Schema) UnmarshalJSON(b []byte) error {
seenIDs[id] = struct{}{}
ids = append(ids, id)
}
- if err := (&Schema{fields: fields, IdentifierFieldIDs:
ids}).ValidateIdentifierFields(); err != nil {
+ if err := (&Schema{fields: fields, identifierFieldIDs:
ids}).ValidateIdentifierFields(); err != nil {
return err
}
s.ID = aux.ID
- s.IdentifierFieldIDs = ids
+ s.identifierFieldIDs = ids
s.fields = fields
s.idToName.Store(nil)
s.idToField.Store(nil)
@@ -468,7 +474,7 @@ func (s *Schema) UnmarshalJSON(b []byte) error {
}
func (s *Schema) MarshalJSON() ([]byte, error) {
- ids := s.IdentifierFieldIDs
+ ids := s.identifierFieldIDs
if ids == nil {
ids = []int{}
}
@@ -519,16 +525,16 @@ func cloneType(t Type) Type {
switch typed := t.(type) {
case *StructType:
- return &StructType{FieldList: cloneFields(typed.FieldList)}
+ return &StructType{fields: cloneFields(typed.fields)}
case *ListType:
cloned := *typed
- cloned.Element = cloneType(typed.Element)
+ cloned.element = cloneType(typed.element)
return &cloned
case *MapType:
cloned := *typed
- cloned.KeyType = cloneType(typed.KeyType)
- cloned.ValueType = cloneType(typed.ValueType)
+ cloned.keyType = cloneType(typed.keyType)
+ cloned.valueType = cloneType(typed.valueType)
return &cloned
default:
@@ -709,7 +715,7 @@ func (s *Schema) Equals(other *Schema) bool {
return false
}
- if !slices.Equal(s.IdentifierFieldIDs, other.IdentifierFieldIDs) {
+ if !slices.Equal(s.identifierFieldIDs, other.identifierFieldIDs) {
return false
}
@@ -741,15 +747,15 @@ func highestFieldIDType(typ Type) int {
switch typ := typ.(type) {
case *StructType:
if typ != nil {
- return highestFieldIDFields(typ.FieldList)
+ return highestFieldIDFields(typ.fields)
}
case *ListType:
if typ != nil {
- return max(typ.ElementID,
highestFieldIDType(typ.Element))
+ return max(typ.elementID,
highestFieldIDType(typ.element))
}
case *MapType:
if typ != nil {
- return max(typ.KeyID, typ.ValueID,
highestFieldIDType(typ.KeyType), highestFieldIDType(typ.ValueType))
+ return max(typ.keyID, typ.valueID,
highestFieldIDType(typ.keyType), highestFieldIDType(typ.valueType))
}
}
@@ -919,12 +925,12 @@ func Visit[T any](sc *Schema, visitor SchemaVisitor[T])
(res T, err error) {
}
func visitStruct[T any](obj StructType, visitor SchemaVisitor[T]) T {
- results := make([]T, len(obj.FieldList))
+ results := make([]T, len(obj.fields))
bf, _ := visitor.(BeforeFieldVisitor)
af, _ := visitor.(AfterFieldVisitor)
- for i, f := range obj.FieldList {
+ for i, f := range obj.fields {
if bf != nil {
bf.BeforeField(f)
}
@@ -1091,9 +1097,9 @@ func PreOrderVisit[T any](sc *Schema, visitor
PreOrderSchemaVisitor[T]) (res T,
}
func visitStructPreOrder[T any](obj StructType, visitor
PreOrderSchemaVisitor[T]) T {
- results := make([]func() T, len(obj.FieldList))
+ results := make([]func() T, len(obj.fields))
- for i, f := range obj.FieldList {
+ for i, f := range obj.fields {
results[i] = func() T {
return visitFieldPreOrder(f, visitor)
}
@@ -1159,14 +1165,14 @@ func (i *indexByID) Field(field NestedField, _
map[int]NestedField) map[int]Nest
}
func (i *indexByID) List(list ListType, _ map[int]NestedField)
map[int]NestedField {
- i.index[list.ElementID] = list.ElementField()
+ i.index[list.elementID] = list.ElementField()
return i.index
}
func (i *indexByID) Map(mapType MapType, _, _ map[int]NestedField)
map[int]NestedField {
- i.index[mapType.KeyID] = mapType.KeyField()
- i.index[mapType.ValueID] = mapType.ValueField()
+ i.index[mapType.keyID] = mapType.KeyField()
+ i.index[mapType.valueID] = mapType.ValueField()
return i.index
}
@@ -1312,14 +1318,14 @@ func (i *indexByName) Field(field NestedField, _
map[string]int) map[string]int
}
func (i *indexByName) List(list ListType, _ map[string]int) map[string]int {
- i.addField(list.ElementField().Name, list.ElementID)
+ i.addField(list.ElementField().Name, list.elementID)
return i.index
}
func (i *indexByName) Map(mapType MapType, _, _ map[string]int) map[string]int
{
- i.addField(mapType.KeyField().Name, mapType.KeyID)
- i.addField(mapType.ValueField().Name, mapType.ValueID)
+ i.addField(mapType.KeyField().Name, mapType.keyID)
+ i.addField(mapType.ValueField().Name, mapType.valueID)
return i.index
}
@@ -1368,8 +1374,8 @@ func PruneColumns(schema *Schema, selected map[int]Void,
selectFullTypes bool) (
n = &StructType{}
}
- newIdentifierIDs := make([]int, 0, len(schema.IdentifierFieldIDs))
- for _, id := range schema.IdentifierFieldIDs {
+ newIdentifierIDs := make([]int, 0, len(schema.identifierFieldIDs))
+ for _, id := range schema.identifierFieldIDs {
if _, ok := selected[id]; ok {
newIdentifierIDs = append(newIdentifierIDs, id)
}
@@ -1378,7 +1384,7 @@ func PruneColumns(schema *Schema, selected map[int]Void,
selectFullTypes bool) (
return &Schema{
fields: n.Fields(),
ID: schema.ID,
- IdentifierFieldIDs: newIdentifierIDs,
+ identifierFieldIDs: newIdentifierIDs,
}, nil
}
@@ -1392,7 +1398,7 @@ func (p *pruneColVisitor) Schema(_ *Schema, structResult
Type) Type {
}
func (p *pruneColVisitor) Struct(st StructType, fieldResults []Type) Type {
- selected, fields := []NestedField{}, st.FieldList
+ selected, fields := []NestedField{}, st.fields
sameType := true
for i, t := range fieldResults {
@@ -1419,7 +1425,7 @@ func (p *pruneColVisitor) Struct(st StructType,
fieldResults []Type) Type {
// nothing changed, return the original
return &st
} else {
- return &StructType{FieldList: selected}
+ return &StructType{fields: selected}
}
}
@@ -1458,7 +1464,7 @@ func (p *pruneColVisitor) Field(field NestedField,
fieldResult Type) Type {
}
func (p *pruneColVisitor) List(list ListType, elemResult Type) Type {
- _, ok := p.selected[list.ElementID]
+ _, ok := p.selected[list.elementID]
if !ok {
if elemResult != nil {
return p.projectList(&list, elemResult)
@@ -1471,29 +1477,29 @@ func (p *pruneColVisitor) List(list ListType,
elemResult Type) Type {
return &list
}
- _, ok = list.Element.(*StructType)
- if list.Element != nil && ok {
+ _, ok = list.element.(*StructType)
+ if list.element != nil && ok {
projected := p.projectSelectedStruct(elemResult)
return p.projectList(&list, projected)
}
- if _, ok = list.Element.(PrimitiveType); !ok {
+ if _, ok = list.element.(PrimitiveType); !ok {
panic(fmt.Errorf("%w: cannot explicitly project List or Map
types, %d of type %s was selected",
- ErrInvalidSchema, list.ElementID, list.Element))
+ ErrInvalidSchema, list.elementID, list.element))
}
return &list
}
func (p *pruneColVisitor) Map(mapType MapType, keyResult, valueResult Type)
Type {
- _, ok := p.selected[mapType.ValueID]
+ _, ok := p.selected[mapType.valueID]
if !ok {
if valueResult != nil {
return p.projectMap(&mapType, valueResult)
}
- if _, ok = p.selected[mapType.KeyID]; ok {
+ if _, ok = p.selected[mapType.keyID]; ok {
return &mapType
}
@@ -1504,16 +1510,16 @@ func (p *pruneColVisitor) Map(mapType MapType,
keyResult, valueResult Type) Type
return &mapType
}
- _, ok = mapType.ValueType.(*StructType)
- if mapType.ValueType != nil && ok {
+ _, ok = mapType.valueType.(*StructType)
+ if mapType.valueType != nil && ok {
projected := p.projectSelectedStruct(valueResult)
return p.projectMap(&mapType, projected)
}
- if _, ok = mapType.ValueType.(PrimitiveType); !ok {
+ if _, ok = mapType.valueType.(PrimitiveType); !ok {
panic(fmt.Errorf("%w: cannot explicitly project List or Map
types, Map value %d of type %s was selected",
- ErrInvalidSchema, mapType.ValueID, mapType.ValueType))
+ ErrInvalidSchema, mapType.valueID, mapType.valueType))
}
return &mapType
@@ -1535,27 +1541,27 @@ func (*pruneColVisitor) projectSelectedStruct(projected
Type) *StructType {
}
func (*pruneColVisitor) projectList(listType *ListType, elementResult Type)
*ListType {
- if listType.Element.Equals(elementResult) {
+ if listType.element.Equals(elementResult) {
return listType
}
return &ListType{
- ElementID: listType.ElementID, Element: elementResult,
- ElementRequired: listType.ElementRequired,
+ elementID: listType.elementID, element: elementResult,
+ elementRequired: listType.elementRequired,
}
}
func (*pruneColVisitor) projectMap(mapType *MapType, valueResult Type)
*MapType {
- if mapType.ValueType.Equals(valueResult) {
+ if mapType.valueType.Equals(valueResult) {
return mapType
}
return &MapType{
- KeyID: mapType.KeyID,
- ValueID: mapType.ValueID,
- KeyType: mapType.KeyType,
- ValueType: valueResult,
- ValueRequired: mapType.ValueRequired,
+ keyID: mapType.keyID,
+ valueID: mapType.valueID,
+ keyType: mapType.keyType,
+ valueType: valueResult,
+ valueRequired: mapType.valueRequired,
}
}
@@ -1592,7 +1598,7 @@ func (i *indexParents) Struct(st StructType, _
[]map[int]int) map[int]int {
stackLen := len(i.idStack)
if stackLen > 0 {
parent = i.idStack[stackLen-1]
- for _, f := range st.FieldList {
+ for _, f := range st.fields {
i.idToParent[f.ID] = parent
}
}
@@ -1605,15 +1611,15 @@ func (i *indexParents) Field(NestedField, map[int]int)
map[int]int {
}
func (i *indexParents) List(list ListType, _ map[int]int) map[int]int {
- i.idToParent[list.ElementID] = i.idStack[len(i.idStack)-1]
+ i.idToParent[list.elementID] = i.idStack[len(i.idStack)-1]
return i.idToParent
}
func (i *indexParents) Map(mapType MapType, _, _ map[int]int) map[int]int {
parent := i.idStack[len(i.idStack)-1]
- i.idToParent[mapType.KeyID] = parent
- i.idToParent[mapType.ValueID] = parent
+ i.idToParent[mapType.keyID] = parent
+ i.idToParent[mapType.valueID] = parent
return i.idToParent
}
@@ -1634,7 +1640,7 @@ func (buildPosAccessors) Schema(_ *Schema, structResult
map[int]accessor) map[in
func (buildPosAccessors) Struct(st StructType, fieldResults
[]map[int]accessor) map[int]accessor {
result := map[int]accessor{}
- for pos, f := range st.FieldList {
+ for pos, f := range st.fields {
if innerMap := fieldResults[pos]; len(innerMap) != 0 {
for inner, acc := range innerMap {
result[inner] = accessor{pos: pos, inner: &acc}
@@ -1703,13 +1709,13 @@ func (s *setFreshIDs) Schema(_ *Schema, structResult
func() Type) Type {
func (s *setFreshIDs) Struct(st StructType, fieldResults []func() Type) Type {
// Assign all sibling IDs before recursing, matching Java.
- newIDs := make([]int, len(st.FieldList))
- for idx, f := range st.FieldList {
+ newIDs := make([]int, len(st.fields))
+ for idx, f := range st.fields {
newIDs[idx] = s.getAndInc(f.ID)
}
- newFields := make([]NestedField, len(st.FieldList))
- for idx, f := range st.FieldList {
+ newFields := make([]NestedField, len(st.fields))
+ for idx, f := range st.fields {
newFields[idx] = NestedField{
ID: newIDs[idx],
Name: f.Name,
@@ -1721,7 +1727,7 @@ func (s *setFreshIDs) Struct(st StructType, fieldResults
[]func() Type) Type {
}
}
- return &StructType{FieldList: newFields}
+ return &StructType{fields: newFields}
}
func (s *setFreshIDs) Field(_ NestedField, fieldResult func() Type) Type {
@@ -1729,25 +1735,25 @@ func (s *setFreshIDs) Field(_ NestedField, fieldResult
func() Type) Type {
}
func (s *setFreshIDs) List(list ListType, elemResult func() Type) Type {
- elemID := s.getAndInc(list.ElementID)
+ elemID := s.getAndInc(list.elementID)
return &ListType{
- ElementID: elemID,
- Element: elemResult(),
- ElementRequired: list.ElementRequired,
+ elementID: elemID,
+ element: elemResult(),
+ elementRequired: list.elementRequired,
}
}
func (s *setFreshIDs) Map(mapType MapType, keyResult, valueResult func() Type)
Type {
- keyID := s.getAndInc(mapType.KeyID)
- valueID := s.getAndInc(mapType.ValueID)
+ keyID := s.getAndInc(mapType.keyID)
+ valueID := s.getAndInc(mapType.valueID)
return &MapType{
- KeyID: keyID,
- ValueID: valueID,
- KeyType: keyResult(),
- ValueType: valueResult(),
- ValueRequired: mapType.ValueRequired,
+ keyID: keyID,
+ valueID: valueID,
+ keyType: keyResult(),
+ valueType: valueResult(),
+ valueRequired: mapType.valueRequired,
}
}
@@ -1791,11 +1797,11 @@ func AssignFreshSchemaIDsWithBase(sc, base *Schema,
nextID func() int) (*Schema,
return nil, err
}
- fields := outType.(*StructType).FieldList
+ fields := outType.(*StructType).fields
var newIdentifierIDs []int
- if len(sc.IdentifierFieldIDs) != 0 {
- newIdentifierIDs = make([]int, len(sc.IdentifierFieldIDs))
- for i, id := range sc.IdentifierFieldIDs {
+ if len(sc.identifierFieldIDs) != 0 {
+ newIdentifierIDs = make([]int, len(sc.identifierFieldIDs))
+ for i, id := range sc.identifierFieldIDs {
newID, ok := visitor.oldIdToNew[id]
if !ok {
return nil, fmt.Errorf("%w: cannot find field
for identifier field id %d", ErrInvalidSchema, id)
@@ -1871,9 +1877,9 @@ func visitStructWithPartner[T, P any](st StructType,
partner P, visitor SchemaWi
bf, _ := visitor.(beforeField)
af, _ := visitor.(afterField)
- fieldResults := make([]T, len(st.FieldList))
+ fieldResults := make([]T, len(st.fields))
- for i, f := range st.FieldList {
+ for i, f := range st.fields {
fieldPartner := accessor.FieldPartner(partner, f.ID, f.Name)
if bf != nil {
bf.BeforeField(f, fieldPartner)
@@ -1902,7 +1908,7 @@ func visitListWithPartner[T, P any](listType ListType,
partner P, visitor Schema
if ble, ok := visitor.(beforeListElem); ok {
ble.BeforeListElement(listType.ElementField(), elemPartner)
}
- elemResult := visitTypeWithPartner(listType.Element, elemPartner,
visitor, accessor)
+ elemResult := visitTypeWithPartner(listType.element, elemPartner,
visitor, accessor)
if ale, ok := visitor.(afterListElem); ok {
ale.AfterListElement(listType.ElementField(), elemPartner)
}
@@ -1931,7 +1937,7 @@ func visitMapWithPartner[T, P any](m MapType, partner P,
visitor SchemaWithPartn
if bmk, ok := visitor.(beforeMapKey); ok {
bmk.BeforeMapKey(m.KeyField(), keyPartner)
}
- keyResult := visitTypeWithPartner(m.KeyType, keyPartner, visitor,
accessor)
+ keyResult := visitTypeWithPartner(m.keyType, keyPartner, visitor,
accessor)
if amk, ok := visitor.(afterMapKey); ok {
amk.AfterMapKey(m.KeyField(), keyPartner)
}
@@ -1940,7 +1946,7 @@ func visitMapWithPartner[T, P any](m MapType, partner P,
visitor SchemaWithPartn
if bmv, ok := visitor.(beforeMapValue); ok {
bmv.BeforeMapValue(m.ValueField(), valPartner)
}
- valResult := visitTypeWithPartner(m.ValueType, valPartner, visitor,
accessor)
+ valResult := visitTypeWithPartner(m.valueType, valPartner, visitor,
accessor)
if amv, ok := visitor.(afterMapValue); ok {
amv.AfterMapValue(m.ValueField(), valPartner)
}
@@ -2055,8 +2061,8 @@ func SanitizeColumnNames(sc *Schema) (*Schema, error) {
return nil, err
}
- return NewSchemaWithIdentifiers(sc.ID, sc.IdentifierFieldIDs,
- result.Type.(*StructType).FieldList...), nil
+ return NewSchemaWithIdentifiers(sc.ID, sc.identifierFieldIDs,
+ result.Type.(*StructType).fields...), nil
}
type sanitizeColumnNameVisitor struct{}
@@ -2091,18 +2097,18 @@ func (sanitizeColumnNameVisitor) Struct(_ StructType,
fieldResults []NestedField
seen[field.Name] = field.ID
}
- return NestedField{Type: &StructType{FieldList: fieldResults}}
+ return NestedField{Type: &StructType{fields: fieldResults}}
}
func (sanitizeColumnNameVisitor) List(list ListType, elemResult NestedField)
NestedField {
- list.Element = elemResult.Type
+ list.element = elemResult.Type
return NestedField{Type: &list}
}
func (sanitizeColumnNameVisitor) Map(mapType MapType, keyResult, valueResult
NestedField) NestedField {
- mapType.KeyType = keyResult.Type
- mapType.ValueType = valueResult.Type
+ mapType.keyType = keyResult.Type
+ mapType.valueType = valueResult.Type
return NestedField{Type: &mapType}
}
diff --git a/schema_clone_internal_test.go b/schema_clone_internal_test.go
new file mode 100644
index 000000000..ce13213db
--- /dev/null
+++ b/schema_clone_internal_test.go
@@ -0,0 +1,256 @@
+// 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 iceberg
+
+// These tests write through the unexported fields of the nested types to
+// check that schema and partition getters hand out copies.
+
+import (
+ "fmt"
+ "runtime"
+ "testing"
+
+ "github.com/apache/iceberg-go/internal"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func TestSchemaAsStructClonesTopLevelFieldList(t *testing.T) {
+ schema := NewSchema(0,
+ NestedField{ID: 1, Name: "foo", Type: PrimitiveTypes.String,
Required: true},
+ )
+
+ structType := schema.AsStruct()
+ structType.fields[0].Name = "hijacked"
+
+ assert.Equal(t, "foo", schema.Field(0).Name)
+}
+
+func TestSchemaAsStructClonesNestedTypes(t *testing.T) {
+ schema := NewSchema(0,
+ NestedField{
+ ID: 1,
+ Name: "person",
+ Type: NewStructType(
+ NestedField{ID: 2, Name: "name", Type:
PrimitiveTypes.String},
+ ),
+ Required: true,
+ },
+ )
+
+ structType := schema.AsStruct()
+ personType, ok := structType.Field(0).Type.(*StructType)
+ require.True(t, ok)
+ personType.fields[0].Name = "full_name"
+
+ clonedPersonType, ok := schema.Field(0).Type.(*StructType)
+ require.True(t, ok)
+ assert.Equal(t, "name", clonedPersonType.Field(0).Name)
+}
+
+func TestSchemaAsStructClonesNestedListTypes(t *testing.T) {
+ schema := NewSchema(0,
+ NestedField{
+ ID: 1,
+ Name: "people",
+ Type: NewListType(2, NewStructType(
+ NestedField{ID: 3, Name: "name", Type:
PrimitiveTypes.String},
+ ), true),
+ Required: true,
+ },
+ )
+
+ structType := schema.AsStruct()
+ listType, ok := structType.Field(0).Type.(*ListType)
+ require.True(t, ok)
+
+ elementType, ok := listType.Element().(*StructType)
+ require.True(t, ok)
+ elementType.fields[0].Name = "full_name"
+
+ clonedListType, ok := schema.Field(0).Type.(*ListType)
+ require.True(t, ok)
+
+ clonedElementType, ok := clonedListType.Element().(*StructType)
+ require.True(t, ok)
+ assert.Equal(t, "name", clonedElementType.Field(0).Name)
+}
+
+func TestSchemaAsStructClonesNestedMapTypes(t *testing.T) {
+ schema := NewSchema(0,
+ NestedField{
+ ID: 1,
+ Name: "people_by_id",
+ Type: NewMapType(2, PrimitiveTypes.String, 3,
NewStructType(
+ NestedField{ID: 4, Name: "name", Type:
PrimitiveTypes.String},
+ ), true),
+ Required: true,
+ },
+ )
+
+ structType := schema.AsStruct()
+ mapType, ok := structType.Field(0).Type.(*MapType)
+ require.True(t, ok)
+
+ valueType, ok := mapType.ValueType().(*StructType)
+ require.True(t, ok)
+ valueType.fields[0].Name = "full_name"
+
+ clonedMapType, ok := schema.Field(0).Type.(*MapType)
+ require.True(t, ok)
+
+ clonedValueType, ok := clonedMapType.ValueType().(*StructType)
+ require.True(t, ok)
+ assert.Equal(t, "name", clonedValueType.Field(0).Name)
+}
+
+func TestSchemaFieldGettersReturnDefensiveCopies(t *testing.T) {
+ schema := NewSchema(0,
+ NestedField{
+ ID: 1,
+ Name: "person",
+ Type: NewStructType(
+ NestedField{ID: 2, Name: "name", Type:
PrimitiveTypes.String},
+ ),
+ },
+ NestedField{
+ ID: 3,
+ Name: "payload",
+ Type: PrimitiveTypes.Binary,
+ InitialDefault: BinaryLiteral{1, 2},
+ WriteDefault: map[string]any{"nested":
[]any{[]byte{3, 4}}},
+ },
+ )
+
+ assertIndependent := func(t *testing.T, personField, payloadField
NestedField) {
+ t.Helper()
+ person, ok := personField.Type.(*StructType)
+ require.True(t, ok)
+ person.fields[0].Name = "hijacked"
+
payloadField.WriteDefault.(map[string]any)["nested"].([]any)[0].([]byte)[0] = 9
+
+ actual, ok := schema.FindFieldByID(2)
+ require.True(t, ok)
+ assert.Equal(t, "name", actual.Name)
+ payload, ok := schema.FindFieldByID(3)
+ require.True(t, ok)
+ assert.Equal(t, "0102", payload.InitialDefault)
+ assert.Equal(t, map[string]any{"nested": []any{[]byte{3, 4}}},
payload.WriteDefault)
+ }
+
+ t.Run("Field", func(t *testing.T) {
+ assertIndependent(t, schema.Field(0), schema.Field(1))
+ })
+ t.Run("Fields", func(t *testing.T) {
+ fields := schema.Fields()
+ assertIndependent(t, fields[0], fields[1])
+ })
+ t.Run("FindFieldByID", func(t *testing.T) {
+ person, ok := schema.FindFieldByID(1)
+ require.True(t, ok)
+ payload, ok := schema.FindFieldByID(3)
+ require.True(t, ok)
+ assertIndependent(t, person, payload)
+ })
+ t.Run("FindFieldByName", func(t *testing.T) {
+ person, ok := schema.FindFieldByName("person")
+ require.True(t, ok)
+ payload, ok := schema.FindFieldByName("payload")
+ require.True(t, ok)
+ assertIndependent(t, person, payload)
+ })
+ t.Run("FindFieldByNameCaseInsensitive", func(t *testing.T) {
+ person, ok := schema.FindFieldByNameCaseInsensitive("PERSON")
+ require.True(t, ok)
+ payload, ok := schema.FindFieldByNameCaseInsensitive("PAYLOAD")
+ require.True(t, ok)
+ assertIndependent(t, person, payload)
+ })
+ t.Run("FindTypeByID", func(t *testing.T) {
+ typ, ok := schema.FindTypeByID(1)
+ require.True(t, ok)
+ person, ok := typ.(*StructType)
+ require.True(t, ok)
+ person.fields[0].Name = "hijacked"
+
+ actual, ok := schema.FindFieldByID(2)
+ require.True(t, ok)
+ assert.Equal(t, "name", actual.Name)
+ })
+ t.Run("FlatFields", func(t *testing.T) {
+ fields, err := schema.FlatFields()
+ require.NoError(t, err)
+ byID := make(map[int]NestedField)
+ for field := range fields {
+ byID[field.ID] = field
+ }
+ assertIndependent(t, byID[1], byID[3])
+ })
+}
+
+func TestSchemaFieldRefLookupDoesNotAllocate(t *testing.T) {
+ children := make([]NestedField, 50)
+ for i := range children {
+ children[i] = NestedField{
+ ID: i + 2, Name: fmt.Sprintf("child_%d", i), Type:
PrimitiveTypes.String,
+ }
+ }
+ schema := NewSchema(0, NestedField{
+ ID: 1, Name: "parent", Type: NewStructType(children...),
+ })
+ _, ok := schema.FindFieldByIDRef(1, internal.SchemaRef{})
+ require.True(t, ok)
+
+ var field NestedField
+ assert.Zero(t, testing.AllocsPerRun(100, func() {
+ field, ok = schema.FindFieldByIDRef(1, internal.SchemaRef{})
+ runtime.KeepAlive(field)
+ }))
+ require.True(t, ok)
+ assert.Equal(t, 1, field.ID)
+
+ var fields []NestedField
+ assert.Zero(t, testing.AllocsPerRun(100, func() {
+ fields = schema.FieldsRef(internal.SchemaRef{})
+ runtime.KeepAlive(fields)
+ }))
+ assert.Len(t, fields, 1)
+
+ parent := field.Type.(*StructType)
+ parent.fields[0].Name = "shared_child"
+ shared, ok := schema.FindFieldByIDRef(1, internal.SchemaRef{})
+ require.True(t, ok)
+ sharedParent := shared.Type.(*StructType)
+ assert.Equal(t, "shared_child", sharedParent.Field(0).Name)
+}
+
+func TestPartitionTypeReturnsIndependentFields(t *testing.T) {
+ schema := NewSchema(0, NestedField{ID: 1, Name: "value", Type:
StringType{}})
+ spec := NewPartitionSpec(PartitionField{
+ SourceIDs: []int{1}, FieldID: 1000, Name: "value", Transform:
IdentityTransform{},
+ })
+ first := spec.PartitionType(schema)
+ second := spec.PartitionType(schema)
+ first.fields[0] = NestedField{ID: 2000, Name: "changed", Type:
Int64Type{}, Required: true}
+
+ want := []NestedField{{ID: 1000, Name: "value", Type: StringType{}}}
+ require.Equal(t, want, second.Fields())
+ require.Equal(t, want, spec.PartitionType(schema).Fields())
+ require.Equal(t, "value", spec.Field(0).Name)
+ require.Equal(t, 1000, spec.Field(0).FieldID)
+}
diff --git a/schema_column_path_test.go b/schema_column_path_test.go
index b52ff75a2..5221f500c 100644
--- a/schema_column_path_test.go
+++ b/schema_column_path_test.go
@@ -69,12 +69,12 @@ func TestColumnPathSegmentsContainers(t *testing.T) {
schema := NewSchema(0,
NestedField{ID: 1, Name: "items", Type: &ListType{
- ElementID: 2,
- Element: &StructType{FieldList: []NestedField{{ID: 3,
Name: "pay.load", Type: VariantType{}}}},
+ elementID: 2,
+ element: &StructType{fields: []NestedField{{ID: 3,
Name: "pay.load", Type: VariantType{}}}},
}},
NestedField{ID: 4, Name: "attributes", Type: &MapType{
- KeyID: 5, KeyType: PrimitiveTypes.String,
- ValueID: 6, ValueType: &StructType{FieldList:
[]NestedField{{ID: 7, Name: "pay.load", Type: VariantType{}}}},
+ keyID: 5, keyType: PrimitiveTypes.String,
+ valueID: 6, valueType: &StructType{fields:
[]NestedField{{ID: 7, Name: "pay.load", Type: VariantType{}}}},
}},
)
for _, tt := range []struct {
@@ -121,7 +121,7 @@ func TestTranslateColumnNamesForScanNestedSourcePath(t
*testing.T) {
func columnPathTestSchema(names []string) *Schema {
field := NestedField{ID: len(names), Name: names[len(names)-1], Type:
VariantType{}}
for i := len(names) - 2; i >= 0; i-- {
- field = NestedField{ID: i + 1, Name: names[i], Type:
&StructType{FieldList: []NestedField{field}}}
+ field = NestedField{ID: i + 1, Name: names[i], Type:
&StructType{fields: []NestedField{field}}}
}
return NewSchema(0, field)
diff --git a/schema_compatibility.go b/schema_compatibility.go
index fe4468848..641a3419f 100644
--- a/schema_compatibility.go
+++ b/schema_compatibility.go
@@ -118,13 +118,13 @@ func (c *compatibilityChecker) Struct(readStruct
StructType, fieldErrors []func(
}
if c.checkOrdering {
- ordinals := make(map[int]int, len(st.FieldList))
- for i, f := range st.FieldList {
+ ordinals := make(map[int]int, len(st.fields))
+ for i, f := range st.fields {
ordinals[f.ID] = i
}
lastOrdinal, lastName := -1, ""
- for _, readField := range readStruct.FieldList {
+ for _, readField := range readStruct.fields {
ordinal, ok := ordinals[readField.ID]
if !ok {
continue
@@ -155,7 +155,7 @@ func (c *compatibilityChecker) Field(readField NestedField,
fieldErrors func() [
writeField NestedField
found bool
)
- for _, f := range st.FieldList {
+ for _, f := range st.fields {
if f.ID == readField.ID {
writeField, found = f, true
@@ -198,11 +198,11 @@ func (c *compatibilityChecker) List(readList ListType,
elementErrors func() []st
}
var errs []string
- if readList.ElementRequired && !list.ElementRequired {
+ if readList.elementRequired && !list.elementRequired {
errs = append(errs, ": elements should be required, but are
optional")
}
- c.current, c.inContainer = list.Element, true
+ c.current, c.inContainer = list.element, true
defer func() { c.current = list }()
return append(errs, elementErrors()...)
@@ -216,14 +216,14 @@ func (c *compatibilityChecker) Map(readMap MapType,
keyErrors, valueErrors func(
defer func() { c.current = m }()
var errs []string
- if readMap.ValueRequired && !m.ValueRequired {
+ if readMap.valueRequired && !m.valueRequired {
errs = append(errs, ": values should be required, but are
optional")
}
- c.current, c.inContainer = m.KeyType, true
+ c.current, c.inContainer = m.keyType, true
errs = append(errs, keyErrors()...)
- c.current, c.inContainer = m.ValueType, true
+ c.current, c.inContainer = m.valueType, true
return append(errs, valueErrors()...)
}
diff --git a/schema_conversions.go b/schema_conversions.go
index e23df9961..1bb73eb51 100644
--- a/schema_conversions.go
+++ b/schema_conversions.go
@@ -26,8 +26,8 @@ import (
)
func partitionTypeToAvroSchema(t *StructType) (*avro.Schema, error) {
- fields := make([]avro.SchemaField, len(t.FieldList))
- for i, f := range t.FieldList {
+ fields := make([]avro.SchemaField, len(t.fields))
+ for i, f := range t.fields {
var node avro.SchemaNode
switch typ := f.Type.(type) {
case Int32Type:
diff --git a/schema_conversions_test.go b/schema_conversions_test.go
index 516a8d51e..e2373230d 100644
--- a/schema_conversions_test.go
+++ b/schema_conversions_test.go
@@ -31,8 +31,8 @@ import (
)
func partitionTypeToAvroSchemaNonNullable(t *StructType) (*avro.Schema, error)
{
- fields := make([]avro.SchemaField, len(t.FieldList))
- for i, f := range t.FieldList {
+ fields := make([]avro.SchemaField, len(t.fields))
+ for i, f := range t.fields {
var node avro.SchemaNode
switch typ := f.Type.(type) {
case Int32Type:
@@ -89,7 +89,7 @@ func partitionTypeToAvroSchemaNonNullable(t *StructType)
(*avro.Schema, error) {
func TestPartitionTypeToAvroSchemaNullableAndNonNullable(t *testing.T) {
partitionType := &StructType{
- FieldList: []NestedField{
+ fields: []NestedField{
{ID: 1, Name: "int32_col", Type: Int32Type{}, Required:
false},
{ID: 2, Name: "int64_col", Type: Int64Type{}, Required:
false},
{ID: 3, Name: "float32_col", Type: Float32Type{},
Required: false},
@@ -165,7 +165,7 @@ func TestPartitionTypeToAvroSchemaNullableAndNonNullable(t
*testing.T) {
}
func TestPartitionTypeToAvroSchemaUnknownType(t *testing.T) {
- partitionType := &StructType{FieldList: []NestedField{
+ partitionType := &StructType{fields: []NestedField{
{ID: 1, Name: "dropped", Type: UnknownType{}, Required: false},
}}
@@ -192,21 +192,21 @@ func TestPartitionTypeToAvroSchemaDuplicateNamedTypes(t
*testing.T) {
}{
{
"two uuid fields",
- &StructType{FieldList: []NestedField{
+ &StructType{fields: []NestedField{
{ID: 1, Name: "a", Type: UUIDType{}, Required:
false},
{ID: 2, Name: "b", Type: UUIDType{}, Required:
false},
}},
},
{
"two fixed fields same size",
- &StructType{FieldList: []NestedField{
+ &StructType{fields: []NestedField{
{ID: 1, Name: "a", Type: FixedType{len: 8},
Required: false},
{ID: 2, Name: "b", Type: FixedType{len: 8},
Required: false},
}},
},
{
"two decimal fields same precision/scale",
- &StructType{FieldList: []NestedField{
+ &StructType{fields: []NestedField{
{ID: 1, Name: "a", Type: DecimalType{precision:
10, scale: 2}, Required: false},
{ID: 2, Name: "b", Type: DecimalType{precision:
10, scale: 2}, Required: false},
}},
@@ -237,7 +237,7 @@ func TestDayTransformPartitionAvroDateEncoding(t
*testing.T) {
// PartitionType now returns DateType for day-transform fields.
partitionType := spec.PartitionType(schema)
- require.Equal(t, PrimitiveTypes.Date, partitionType.FieldList[0].Type,
+ require.Equal(t, PrimitiveTypes.Date, partitionType.fields[0].Type,
"PartitionType must map DayTransform result to DateType")
avroSchema, err := partitionTypeToAvroSchema(partitionType)
@@ -304,7 +304,7 @@ func TestNanosecondPartitionAvroSchema(t *testing.T) {
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
- partitionType := &StructType{FieldList: []NestedField{
+ partitionType := &StructType{fields: []NestedField{
{ID: 1000, Name: "ts_ns", Type: tc.typ,
Required: false},
}}
diff --git a/schema_highest_field_id_bench_test.go
b/schema_highest_field_id_bench_test.go
index 359888ba5..de18926b5 100644
--- a/schema_highest_field_id_bench_test.go
+++ b/schema_highest_field_id_bench_test.go
@@ -70,7 +70,7 @@ func benchmarkHighestNestedSchema(depth int) *Schema {
field = NestedField{
ID: i + 1,
Name: fmt.Sprintf("level_%d", i),
- Type: &StructType{FieldList: []NestedField{field}},
+ Type: &StructType{fields: []NestedField{field}},
}
}
@@ -85,12 +85,12 @@ func benchmarkHighestMixedSchema(groups int) *Schema {
ID: nextID,
Name: fmt.Sprintf("field_%d", i),
Type: &MapType{
- KeyID: nextID + 1,
- KeyType: PrimitiveTypes.String,
- ValueID: nextID + 2,
- ValueType: &ListType{
- ElementID: nextID + 3,
- Element: &StructType{FieldList:
[]NestedField{{
+ keyID: nextID + 1,
+ keyType: PrimitiveTypes.String,
+ valueID: nextID + 2,
+ valueType: &ListType{
+ elementID: nextID + 3,
+ element: &StructType{fields:
[]NestedField{{
ID: nextID + 4,
Name: "value",
Type: PrimitiveTypes.Int64,
diff --git a/schema_identifier_fields_validation_test.go
b/schema_identifier_fields_validation_test.go
index 8698f7662..cf5ccd5a6 100644
--- a/schema_identifier_fields_validation_test.go
+++ b/schema_identifier_fields_validation_test.go
@@ -35,7 +35,7 @@ func TestValidateIdentifierFields(t *testing.T) {
{"root", []int{1}, []NestedField{requiredID}, ""},
{"nested required struct", []int{2}, []NestedField{{
ID: 1, Name: "outer", Required: true,
- Type: &StructType{FieldList: []NestedField{{
+ Type: &StructType{fields: []NestedField{{
ID: 2, Name: "id", Type: PrimitiveTypes.Int64,
Required: true,
}}},
}}, ""},
@@ -59,23 +59,23 @@ func TestValidateIdentifierFields(t *testing.T) {
ID: 1, Name: "id", Type: &Int64Type{}, Required: true,
}}, ""},
{"struct", []int{1}, []NestedField{{
- ID: 1, Name: "id", Type: &StructType{FieldList: nil},
Required: true,
+ ID: 1, Name: "id", Type: &StructType{fields: nil},
Required: true,
}}, "must be primitive"},
{"optional struct parent", []int{2}, []NestedField{{
ID: 1, Name: "outer",
- Type: &StructType{FieldList: []NestedField{{
+ Type: &StructType{fields: []NestedField{{
ID: 2, Name: "id", Type: PrimitiveTypes.Int64,
Required: true,
}}},
}}, "optional field"},
{"list element", []int{2}, []NestedField{{
ID: 1, Name: "items", Required: true,
- Type: &ListType{ElementID: 2, Element:
PrimitiveTypes.Int64, ElementRequired: true},
+ Type: &ListType{elementID: 2, element:
PrimitiveTypes.Int64, elementRequired: true},
}}, "cannot be nested"},
{"map value", []int{3}, []NestedField{{
ID: 1, Name: "tags", Required: true,
Type: &MapType{
- KeyID: 2, KeyType: PrimitiveTypes.String,
- ValueID: 3, ValueType: PrimitiveTypes.Int64,
ValueRequired: true,
+ keyID: 2, keyType: PrimitiveTypes.String,
+ valueID: 3, valueType: PrimitiveTypes.Int64,
valueRequired: true,
},
}}, "cannot be nested"},
{"duplicate identifier", []int{1, 1},
[]NestedField{requiredID}, "duplicate identifier"},
@@ -100,10 +100,10 @@ func TestValidateIdentifierFields(t *testing.T) {
switch {
case tc.error == "":
require.NoError(t, err)
- require.Equal(t, tc.ids,
read.IdentifierFieldIDs)
+ require.Equal(t, tc.ids,
read.identifierFieldIDs)
case tc.name == "duplicate identifier":
require.NoError(t, err)
- require.Equal(t, []int{1},
read.IdentifierFieldIDs)
+ require.Equal(t, []int{1},
read.identifierFieldIDs)
default:
require.ErrorIs(t, err, ErrInvalidSchema)
require.ErrorContains(t, err, tc.error)
@@ -124,13 +124,13 @@ func TestUnmarshalSchemaDeduplicatesIdentifierIDs(t
*testing.T) {
]
}`), &schema)
require.NoError(t, err)
- require.Equal(t, []int{2, 1}, schema.IdentifierFieldIDs)
+ require.Equal(t, []int{2, 1}, schema.identifierFieldIDs)
data, err := json.Marshal(&schema)
require.NoError(t, err)
var roundTrip Schema
require.NoError(t, json.Unmarshal(data, &roundTrip))
- require.Equal(t, []int{2, 1}, roundTrip.IdentifierFieldIDs)
+ require.Equal(t, []int{2, 1}, roundTrip.identifierFieldIDs)
require.True(t, schema.Equals(&roundTrip))
}
@@ -147,5 +147,5 @@ func
TestUnmarshalSchemaRejectsInvalidIdentifierAndKeepsOldState(t *testing.T) {
require.ErrorIs(t, err, ErrInvalidSchema)
require.Equal(t, 7, schema.ID)
require.Equal(t, "original", schema.Field(0).Name)
- require.Empty(t, schema.IdentifierFieldIDs)
+ require.Empty(t, schema.identifierFieldIDs)
}
diff --git a/schema_name_index_bench_test.go b/schema_name_index_bench_test.go
index b147dc608..2b041ea16 100644
--- a/schema_name_index_bench_test.go
+++ b/schema_name_index_bench_test.go
@@ -40,7 +40,7 @@ func benchmarkWideNestedSchema(width, depth int) *Schema {
nextID++
leaves = []NestedField{{
ID: nextID, Name: fmt.Sprintf("nested_%d", level),
- Type: &StructType{FieldList: leaves},
+ Type: &StructType{fields: leaves},
}}
}
diff --git a/schema_name_index_internal_test.go
b/schema_name_index_internal_test.go
index fcb58af20..86de0d771 100644
--- a/schema_name_index_internal_test.go
+++ b/schema_name_index_internal_test.go
@@ -27,12 +27,12 @@ import (
func TestIndexByNameNestedListAliases(t *testing.T) {
schema := NewSchema(1,
- NestedField{ID: 1, Name: "payload", Type:
&StructType{FieldList: []NestedField{
+ NestedField{ID: 1, Name: "payload", Type: &StructType{fields:
[]NestedField{
{ID: 2, Name: "list", Type: &ListType{
- ElementID: 3,
- Element: &StructType{FieldList: []NestedField{
+ elementID: 3,
+ element: &StructType{fields: []NestedField{
{ID: 4, Name: "alpha", Type:
PrimitiveTypes.Int64},
- {ID: 5, Name: "hidden", Type:
&StructType{FieldList: []NestedField{
+ {ID: 5, Name: "hidden", Type:
&StructType{fields: []NestedField{
{ID: 6, Name: "beta", Type:
PrimitiveTypes.String},
}}},
}},
@@ -40,8 +40,8 @@ func TestIndexByNameNestedListAliases(t *testing.T) {
}}},
NestedField{ID: 7, Name: "sibling", Type:
PrimitiveTypes.String},
NestedField{ID: 8, Name: "lookup", Type: &MapType{
- KeyID: 9, KeyType: PrimitiveTypes.String,
- ValueID: 10, ValueType: &StructType{FieldList:
[]NestedField{
+ keyID: 9, keyType: PrimitiveTypes.String,
+ valueID: 10, valueType: &StructType{fields:
[]NestedField{
{ID: 11, Name: "東京", Type:
PrimitiveTypes.Int32},
}},
}},
@@ -89,7 +89,7 @@ func TestIndexByNameDeepSiblingRestoration(t *testing.T) {
for depth := range 32 {
name := "nested_" + strconv.Itoa(depth)
fields = []NestedField{{
- ID: depth + 2, Name: name, Type: &StructType{FieldList:
fields},
+ ID: depth + 2, Name: name, Type: &StructType{fields:
fields},
}}
parts = append([]string{name}, parts...)
}
diff --git a/schema_test.go b/schema_test.go
index 8b09ab873..4d993348d 100644
--- a/schema_test.go
+++ b/schema_test.go
@@ -23,13 +23,11 @@ import (
"os"
"path/filepath"
"reflect"
- "runtime"
"strings"
"sync"
"testing"
"github.com/apache/iceberg-go"
- "github.com/apache/iceberg-go/internal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
@@ -193,215 +191,6 @@ func TestNestedFieldToString(t *testing.T) {
}
}
-func TestSchemaAsStructClonesTopLevelFieldList(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{ID: 1, Name: "foo", Type:
iceberg.PrimitiveTypes.String, Required: true},
- )
-
- structType := schema.AsStruct()
- structType.FieldList[0].Name = "hijacked"
-
- assert.Equal(t, "foo", schema.Field(0).Name)
-}
-
-func TestSchemaAsStructClonesNestedTypes(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{
- ID: 1,
- Name: "person",
- Type: iceberg.NewStructType(
- iceberg.NestedField{ID: 2, Name: "name", Type:
iceberg.PrimitiveTypes.String},
- ),
- Required: true,
- },
- )
-
- structType := schema.AsStruct()
- personType, ok := structType.Field(0).Type.(*iceberg.StructType)
- require.True(t, ok)
- personType.FieldList[0].Name = "full_name"
-
- clonedPersonType, ok := schema.Field(0).Type.(*iceberg.StructType)
- require.True(t, ok)
- assert.Equal(t, "name", clonedPersonType.Field(0).Name)
-}
-
-func TestSchemaAsStructClonesNestedListTypes(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{
- ID: 1,
- Name: "people",
- Type: iceberg.NewListType(2, iceberg.NewStructType(
- iceberg.NestedField{ID: 3, Name: "name", Type:
iceberg.PrimitiveTypes.String},
- ), true),
- Required: true,
- },
- )
-
- structType := schema.AsStruct()
- listType, ok := structType.Field(0).Type.(*iceberg.ListType)
- require.True(t, ok)
-
- elementType, ok := listType.Element.(*iceberg.StructType)
- require.True(t, ok)
- elementType.FieldList[0].Name = "full_name"
-
- clonedListType, ok := schema.Field(0).Type.(*iceberg.ListType)
- require.True(t, ok)
-
- clonedElementType, ok := clonedListType.Element.(*iceberg.StructType)
- require.True(t, ok)
- assert.Equal(t, "name", clonedElementType.Field(0).Name)
-}
-
-func TestSchemaAsStructClonesNestedMapTypes(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{
- ID: 1,
- Name: "people_by_id",
- Type: iceberg.NewMapType(2,
iceberg.PrimitiveTypes.String, 3, iceberg.NewStructType(
- iceberg.NestedField{ID: 4, Name: "name", Type:
iceberg.PrimitiveTypes.String},
- ), true),
- Required: true,
- },
- )
-
- structType := schema.AsStruct()
- mapType, ok := structType.Field(0).Type.(*iceberg.MapType)
- require.True(t, ok)
-
- valueType, ok := mapType.ValueType.(*iceberg.StructType)
- require.True(t, ok)
- valueType.FieldList[0].Name = "full_name"
-
- clonedMapType, ok := schema.Field(0).Type.(*iceberg.MapType)
- require.True(t, ok)
-
- clonedValueType, ok := clonedMapType.ValueType.(*iceberg.StructType)
- require.True(t, ok)
- assert.Equal(t, "name", clonedValueType.Field(0).Name)
-}
-
-func TestSchemaFieldGettersReturnDefensiveCopies(t *testing.T) {
- schema := iceberg.NewSchema(0,
- iceberg.NestedField{
- ID: 1,
- Name: "person",
- Type: iceberg.NewStructType(
- iceberg.NestedField{ID: 2, Name: "name", Type:
iceberg.PrimitiveTypes.String},
- ),
- },
- iceberg.NestedField{
- ID: 3,
- Name: "payload",
- Type: iceberg.PrimitiveTypes.Binary,
- InitialDefault: iceberg.BinaryLiteral{1, 2},
- WriteDefault: map[string]any{"nested":
[]any{[]byte{3, 4}}},
- },
- )
-
- assertIndependent := func(t *testing.T, personField, payloadField
iceberg.NestedField) {
- t.Helper()
- person, ok := personField.Type.(*iceberg.StructType)
- require.True(t, ok)
- person.FieldList[0].Name = "hijacked"
-
payloadField.WriteDefault.(map[string]any)["nested"].([]any)[0].([]byte)[0] = 9
-
- actual, ok := schema.FindFieldByID(2)
- require.True(t, ok)
- assert.Equal(t, "name", actual.Name)
- payload, ok := schema.FindFieldByID(3)
- require.True(t, ok)
- assert.Equal(t, "0102", payload.InitialDefault)
- assert.Equal(t, map[string]any{"nested": []any{[]byte{3, 4}}},
payload.WriteDefault)
- }
-
- t.Run("Field", func(t *testing.T) {
- assertIndependent(t, schema.Field(0), schema.Field(1))
- })
- t.Run("Fields", func(t *testing.T) {
- fields := schema.Fields()
- assertIndependent(t, fields[0], fields[1])
- })
- t.Run("FindFieldByID", func(t *testing.T) {
- person, ok := schema.FindFieldByID(1)
- require.True(t, ok)
- payload, ok := schema.FindFieldByID(3)
- require.True(t, ok)
- assertIndependent(t, person, payload)
- })
- t.Run("FindFieldByName", func(t *testing.T) {
- person, ok := schema.FindFieldByName("person")
- require.True(t, ok)
- payload, ok := schema.FindFieldByName("payload")
- require.True(t, ok)
- assertIndependent(t, person, payload)
- })
- t.Run("FindFieldByNameCaseInsensitive", func(t *testing.T) {
- person, ok := schema.FindFieldByNameCaseInsensitive("PERSON")
- require.True(t, ok)
- payload, ok := schema.FindFieldByNameCaseInsensitive("PAYLOAD")
- require.True(t, ok)
- assertIndependent(t, person, payload)
- })
- t.Run("FindTypeByID", func(t *testing.T) {
- typ, ok := schema.FindTypeByID(1)
- require.True(t, ok)
- person, ok := typ.(*iceberg.StructType)
- require.True(t, ok)
- person.FieldList[0].Name = "hijacked"
-
- actual, ok := schema.FindFieldByID(2)
- require.True(t, ok)
- assert.Equal(t, "name", actual.Name)
- })
- t.Run("FlatFields", func(t *testing.T) {
- fields, err := schema.FlatFields()
- require.NoError(t, err)
- byID := make(map[int]iceberg.NestedField)
- for field := range fields {
- byID[field.ID] = field
- }
- assertIndependent(t, byID[1], byID[3])
- })
-}
-
-func TestSchemaFieldRefLookupDoesNotAllocate(t *testing.T) {
- children := make([]iceberg.NestedField, 50)
- for i := range children {
- children[i] = iceberg.NestedField{
- ID: i + 2, Name: fmt.Sprintf("child_%d", i), Type:
iceberg.PrimitiveTypes.String,
- }
- }
- schema := iceberg.NewSchema(0, iceberg.NestedField{
- ID: 1, Name: "parent", Type: iceberg.NewStructType(children...),
- })
- _, ok := schema.FindFieldByIDRef(1, internal.SchemaRef{})
- require.True(t, ok)
-
- var field iceberg.NestedField
- assert.Zero(t, testing.AllocsPerRun(100, func() {
- field, ok = schema.FindFieldByIDRef(1, internal.SchemaRef{})
- runtime.KeepAlive(field)
- }))
- require.True(t, ok)
- assert.Equal(t, 1, field.ID)
-
- var fields []iceberg.NestedField
- assert.Zero(t, testing.AllocsPerRun(100, func() {
- fields = schema.FieldsRef(internal.SchemaRef{})
- runtime.KeepAlive(fields)
- }))
- assert.Len(t, fields, 1)
-
- parent := field.Type.(*iceberg.StructType)
- parent.FieldList[0].Name = "shared_child"
- shared, ok := schema.FindFieldByIDRef(1, internal.SchemaRef{})
- require.True(t, ok)
- sharedParent := shared.Type.(*iceberg.StructType)
- assert.Equal(t, "shared_child", sharedParent.Field(0).Name)
-}
-
func TestSchemaIndexByIDVisitor(t *testing.T) {
index, err := iceberg.IndexByID(tableSchemaNested)
require.NoError(t, err)
@@ -635,7 +424,9 @@ func TestMarshalSchemaIncludesExportedFields(t *testing.T) {
require.Contains(t, marshaled, "type")
require.Contains(t, marshaled, "fields")
- wantKeys := 2
+ require.Contains(t, marshaled, "identifier-field-ids")
+ assert.JSONEq(t, `[1]`, string(marshaled["identifier-field-ids"]))
+ wantKeys := 3
value := reflect.ValueOf(schema).Elem()
for i := range value.NumField() {
field := value.Type().Field(i)
@@ -711,7 +502,7 @@ func TestUnmarshalSchemaAcceptsLegacyV1Envelope(t
*testing.T) {
}`), &schema))
assert.Zero(t, schema.ID)
- assert.Empty(t, schema.IdentifierFieldIDs)
+ assert.Empty(t, schema.IdentifierFieldIDs())
}
func TestMarshalSchemaWritesEmptyFieldsArray(t *testing.T) {
@@ -745,7 +536,7 @@ func TestUnmarshalSchemaReplacesExistingState(t *testing.T)
{
}`), schema))
assert.Zero(t, schema.ID)
- assert.Empty(t, schema.IdentifierFieldIDs)
+ assert.Empty(t, schema.IdentifierFieldIDs())
assert.Equal(t, 1, schema.NumFields())
_, ok = schema.FindFieldByID(1)
assert.False(t, ok)
@@ -787,7 +578,7 @@ func TestUnmarshalSchemaPreservesExistingStateOnError(t
*testing.T) {
require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
assert.Equal(t, 7, schema.ID)
- assert.Equal(t, []int{1}, schema.IdentifierFieldIDs)
+ assert.Equal(t, []int{1}, schema.IdentifierFieldIDs())
assert.Equal(t, 1, schema.NumFields())
field, ok := schema.FindFieldByID(1)
require.True(t, ok)
@@ -804,6 +595,19 @@ func TestUnmarshalSchemaPreservesExistingStateOnError(t
*testing.T) {
assert.False(t, schema.FieldHasOptionalParent(1))
}
+func TestSchemaIdentifierFieldIDsAreCopied(t *testing.T) {
+ ids := []int{1}
+ schema := iceberg.NewSchemaWithIdentifiers(1, ids,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ )
+
+ ids[0] = 99
+ got := schema.IdentifierFieldIDs()
+ got[0] = 98
+
+ assert.Equal(t, []int{1}, schema.IdentifierFieldIDs())
+}
+
func TestUnmarshalSchemaPreservesExistingStateOnFieldDecodeError(t *testing.T)
{
schema := iceberg.NewSchemaWithIdentifiers(7, []int{1},
iceberg.NestedField{ID: 1, Name: "old", Type:
iceberg.PrimitiveTypes.String},
@@ -818,7 +622,7 @@ func
TestUnmarshalSchemaPreservesExistingStateOnFieldDecodeError(t *testing.T) {
require.Error(t, err)
assert.Equal(t, 7, schema.ID)
- assert.Equal(t, []int{1}, schema.IdentifierFieldIDs)
+ assert.Equal(t, []int{1}, schema.IdentifierFieldIDs())
assert.Equal(t, "old", schema.Field(0).Name)
_, ok = schema.FindFieldByID(1)
assert.True(t, ok)
@@ -1141,7 +945,7 @@ func TestUnmarshalSchemaAllowsZeroCollectionFieldIDs(t
*testing.T) {
t.Helper()
listType, ok := field.Type.(*iceberg.ListType)
require.True(t, ok)
- assert.Equal(t, 0, listType.ElementID)
+ assert.Equal(t, 0, listType.ElementID())
},
},
{
@@ -1170,7 +974,7 @@ func TestUnmarshalSchemaAllowsZeroCollectionFieldIDs(t
*testing.T) {
t.Helper()
mapType, ok := field.Type.(*iceberg.MapType)
require.True(t, ok)
- assert.Equal(t, 0, mapType.KeyID)
+ assert.Equal(t, 0, mapType.KeyID())
},
},
{
@@ -1199,7 +1003,7 @@ func TestUnmarshalSchemaAllowsZeroCollectionFieldIDs(t
*testing.T) {
t.Helper()
mapType, ok := field.Type.(*iceberg.MapType)
require.True(t, ok)
- assert.Equal(t, 0, mapType.ValueID)
+ assert.Equal(t, 0, mapType.ValueID())
},
},
}
@@ -1585,7 +1389,7 @@ func TestAssignFreshSchemaIDsWithBase(t *testing.T) {
)},
)
assert.True(t, expected.Equals(out), "expected %s, got %s", expected,
out)
- assert.Equal(t, []int{1}, out.IdentifierFieldIDs)
+ assert.Equal(t, []int{1}, out.IdentifierFieldIDs())
assert.Equal(t, 11, lastColumnID, "only new fields should consume IDs")
}
@@ -1706,7 +1510,7 @@ func TestAssignFreshSchemaIDsWithBaseNewIdentifierField(t
*testing.T) {
out, err := iceberg.AssignFreshSchemaIDsWithBase(sc, base, nil)
require.NoError(t, err)
- assert.Equal(t, []int{1, 2}, out.IdentifierFieldIDs)
+ assert.Equal(t, []int{1, 2}, out.IdentifierFieldIDs())
}
func TestAssignFreshSchemaIDsStaleIdentifierField(t *testing.T) {
@@ -1725,7 +1529,7 @@ func TestAssignFreshSchemaIDsWithNilBase(t *testing.T) {
require.NoError(t, err)
assert.True(t, withoutBase.Equals(withBase))
- assert.Equal(t, withoutBase.IdentifierFieldIDs,
withBase.IdentifierFieldIDs)
+ assert.Equal(t, withoutBase.IdentifierFieldIDs(),
withBase.IdentifierFieldIDs())
}
func TestSchemaRoundTrip(t *testing.T) {
@@ -2605,6 +2409,6 @@ func TestSchemaMarshalJSONConcurrentLazyLookups(t
*testing.T) {
{"id": 2, "name": "data", "type": "string",
"required": false}
]
}`, string(data))
- assert.Nil(t, schema.IdentifierFieldIDs)
+ assert.Nil(t, schema.IdentifierFieldIDs())
}
}
diff --git a/table/arrow_filter_plan.go b/table/arrow_filter_plan.go
index a7b7c8865..3e025603d 100644
--- a/table/arrow_filter_plan.go
+++ b/table/arrow_filter_plan.go
@@ -222,27 +222,27 @@ func writePhysicalTypeKey(builder *strings.Builder, typ
iceberg.Type) {
panic(physicalSchemaKeyPanic("nil list type"))
}
builder.WriteByte('l')
- writePhysicalInt(builder, t.ElementID)
- if t.ElementRequired {
+ writePhysicalInt(builder, t.ElementID())
+ if t.ElementRequired() {
builder.WriteByte('1')
} else {
builder.WriteByte('0')
}
- writePhysicalTypeKey(builder, t.Element)
+ writePhysicalTypeKey(builder, t.Element())
case *iceberg.MapType:
if t == nil {
panic(physicalSchemaKeyPanic("nil map type"))
}
builder.WriteByte('m')
- writePhysicalInt(builder, t.KeyID)
- writePhysicalTypeKey(builder, t.KeyType)
- writePhysicalInt(builder, t.ValueID)
- if t.ValueRequired {
+ writePhysicalInt(builder, t.KeyID())
+ writePhysicalTypeKey(builder, t.KeyType())
+ writePhysicalInt(builder, t.ValueID())
+ if t.ValueRequired() {
builder.WriteByte('1')
} else {
builder.WriteByte('0')
}
- writePhysicalTypeKey(builder, t.ValueType)
+ writePhysicalTypeKey(builder, t.ValueType())
case iceberg.BooleanType:
builder.WriteByte('b')
case iceberg.Int32Type:
diff --git a/table/arrow_filter_plan_test.go b/table/arrow_filter_plan_test.go
index 75cc0a54e..b8dfee713 100644
--- a/table/arrow_filter_plan_test.go
+++ b/table/arrow_filter_plan_test.go
@@ -206,10 +206,11 @@ func TestPhysicalSchemaKeyIgnoresMetadata(t *testing.T) {
fields = original.Fields()
fields[0].Doc = "root documentation"
- child := &fields[0].Type.(*iceberg.StructType).FieldList[0]
- child.Doc = "value documentation"
- child.InitialDefault = int64(7)
- child.WriteDefault = int64(9)
+ children := fields[0].Type.(*iceberg.StructType).Fields()
+ children[0].Doc = "value documentation"
+ children[0].InitialDefault = int64(7)
+ children[0].WriteDefault = int64(9)
+ fields[0].Type = iceberg.NewStructType(children...)
withMetadata := iceberg.NewSchemaWithIdentifiers(2, []int{2}, fields...)
metadataKey, err := physicalSchemaKey(withMetadata)
require.NoError(t, err)
@@ -232,38 +233,51 @@ func TestPhysicalSchemaKeyDistinguishesNestedLayouts(t
*testing.T) {
original, err := physicalSchemaKey(schema)
require.NoError(t, err)
+ decimal := iceberg.MustDecimalTypeOf(10, 2)
for _, tc := range []struct {
name string
- change func(*iceberg.StructType)
+ change func(*[]iceberg.NestedField)
}{
- {"field_id", func(s *iceberg.StructType) { s.FieldList[0].ID =
20 }},
- {"field_name", func(s *iceberg.StructType) {
s.FieldList[0].Name = "items:;{}" }},
- {"field_required", func(s *iceberg.StructType) {
s.FieldList[0].Required = true }},
- {"field_order", func(s *iceberg.StructType) { s.FieldList[0],
s.FieldList[1] = s.FieldList[1], s.FieldList[0] }},
- {"list_id", func(s *iceberg.StructType) {
s.FieldList[0].Type.(*iceberg.ListType).ElementID = 30 }},
- {"list_required", func(s *iceberg.StructType) {
s.FieldList[0].Type.(*iceberg.ListType).ElementRequired = true }},
- {"list_type", func(s *iceberg.StructType) {
- s.FieldList[0].Type.(*iceberg.ListType).Element =
iceberg.PrimitiveTypes.Int32
+ {"field_id", func(f *[]iceberg.NestedField) { (*f)[0].ID = 20
}},
+ {"field_name", func(f *[]iceberg.NestedField) { (*f)[0].Name =
"items:;{}" }},
+ {"field_required", func(f *[]iceberg.NestedField) {
(*f)[0].Required = true }},
+ {"field_order", func(f *[]iceberg.NestedField) { (*f)[0],
(*f)[1] = (*f)[1], (*f)[0] }},
+ {"list_id", func(f *[]iceberg.NestedField) {
+ (*f)[0].Type = iceberg.NewListType(30,
iceberg.PrimitiveTypes.Int64, false)
}},
- {"map_key_id", func(s *iceberg.StructType) {
s.FieldList[1].Type.(*iceberg.MapType).KeyID = 50 }},
- {"map_key_type", func(s *iceberg.StructType) {
- s.FieldList[1].Type.(*iceberg.MapType).KeyType =
iceberg.PrimitiveTypes.Int32
+ {"list_required", func(f *[]iceberg.NestedField) {
+ (*f)[0].Type = iceberg.NewListType(3,
iceberg.PrimitiveTypes.Int64, true)
}},
- {"map_value_id", func(s *iceberg.StructType) {
s.FieldList[1].Type.(*iceberg.MapType).ValueID = 60 }},
- {"map_value_required", func(s *iceberg.StructType) {
s.FieldList[1].Type.(*iceberg.MapType).ValueRequired = true }},
- {"decimal_precision", func(s *iceberg.StructType) {
- s.FieldList[1].Type.(*iceberg.MapType).ValueType =
iceberg.MustDecimalTypeOf(11, 2)
+ {"list_type", func(f *[]iceberg.NestedField) {
+ (*f)[0].Type = iceberg.NewListType(3,
iceberg.PrimitiveTypes.Int32, false)
}},
- {"decimal_scale", func(s *iceberg.StructType) {
- s.FieldList[1].Type.(*iceberg.MapType).ValueType =
iceberg.MustDecimalTypeOf(10, 3)
+ {"map_key_id", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(50,
iceberg.PrimitiveTypes.String, 6, decimal, false)
}},
- {"fixed_size", func(s *iceberg.StructType) {
s.FieldList[2].Type = iceberg.MustFixedTypeOf(16) }},
- {"variant_type", func(s *iceberg.StructType) {
s.FieldList[3].Type = iceberg.PrimitiveTypes.Binary }},
- {"empty_struct", func(s *iceberg.StructType) { s.FieldList =
nil }},
+ {"map_key_type", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(5,
iceberg.PrimitiveTypes.Int32, 6, decimal, false)
+ }},
+ {"map_value_id", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(5,
iceberg.PrimitiveTypes.String, 60, decimal, false)
+ }},
+ {"map_value_required", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(5,
iceberg.PrimitiveTypes.String, 6, decimal, true)
+ }},
+ {"decimal_precision", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(5,
iceberg.PrimitiveTypes.String, 6, iceberg.MustDecimalTypeOf(11, 2), false)
+ }},
+ {"decimal_scale", func(f *[]iceberg.NestedField) {
+ (*f)[1].Type = iceberg.NewMapType(5,
iceberg.PrimitiveTypes.String, 6, iceberg.MustDecimalTypeOf(10, 3), false)
+ }},
+ {"fixed_size", func(f *[]iceberg.NestedField) { (*f)[2].Type =
iceberg.MustFixedTypeOf(16) }},
+ {"variant_type", func(f *[]iceberg.NestedField) { (*f)[3].Type
= iceberg.PrimitiveTypes.Binary }},
+ {"empty_struct", func(f *[]iceberg.NestedField) { *f = nil }},
} {
t.Run(tc.name, func(t *testing.T) {
fields := schema.Fields()
- tc.change(fields[0].Type.(*iceberg.StructType))
+ children :=
fields[0].Type.(*iceberg.StructType).Fields()
+ tc.change(&children)
+ fields[0].Type = iceberg.NewStructType(children...)
key, err := physicalSchemaKey(iceberg.NewSchema(1,
fields...))
require.NoError(t, err)
assert.NotEqual(t, original, key)
diff --git a/table/arrow_scanner.go b/table/arrow_scanner.go
index c5e1ed79d..24fa9e37e 100644
--- a/table/arrow_scanner.go
+++ b/table/arrow_scanner.go
@@ -1729,11 +1729,11 @@ func collectLeafIDs(typ iceberg.Type, fieldID int,
idset set[int]) {
switch t := typ.(type) {
case *iceberg.MapType:
// For maps, collect leaf IDs from both key and value
- collectLeafIDs(t.KeyType, t.KeyID, idset)
- collectLeafIDs(t.ValueType, t.ValueID, idset)
+ collectLeafIDs(t.KeyType(), t.KeyID(), idset)
+ collectLeafIDs(t.ValueType(), t.ValueID(), idset)
case *iceberg.ListType:
// For lists, collect leaf IDs from the element
- collectLeafIDs(t.Element, t.ElementID, idset)
+ collectLeafIDs(t.Element(), t.ElementID(), idset)
case *iceberg.StructType:
// For structs, collect leaf IDs from all fields
for _, field := range t.Fields() {
diff --git a/table/changelog_normalization.go b/table/changelog_normalization.go
index ec8851655..d9f4c8a76 100644
--- a/table/changelog_normalization.go
+++ b/table/changelog_normalization.go
@@ -287,7 +287,7 @@ func changelogIdentifiers(schema *iceberg.Schema, opts
ChangelogNormalizationOpt
if !opts.ComputeUpdates {
return nil, nil
}
- ids := slices.Clone(schema.IdentifierFieldIDs)
+ ids := schema.IdentifierFieldIDs()
if len(opts.IdentifierFields) != 0 {
ids = make([]int, 0, len(opts.IdentifierFields))
for _, name := range opts.IdentifierFields {
diff --git a/table/equality_delete_reader.go b/table/equality_delete_reader.go
index bfd3545c6..58eda276b 100644
--- a/table/equality_delete_reader.go
+++ b/table/equality_delete_reader.go
@@ -569,7 +569,7 @@ func equalityDeleteReadSchema(
fields := mergeEqualityProjectionFields(fileSchema.Fields(), missing)
- return iceberg.NewSchemaWithIdentifiers(fileSchema.ID,
fileSchema.IdentifierFieldIDs, fields...), nil
+ return iceberg.NewSchemaWithIdentifiers(fileSchema.ID,
fileSchema.IdentifierFieldIDs(), fields...), nil
}
func mergeEqualityProjectionFields(
diff --git a/table/inspect/inspect_test.go b/table/inspect/inspect_test.go
index 575cc08db..bc370ad7b 100644
--- a/table/inspect/inspect_test.go
+++ b/table/inspect/inspect_test.go
@@ -547,10 +547,10 @@ func TestInspectSnapshotsSchema(t *testing.T) {
m, ok := fields[5].Type.(*iceberg.MapType)
require.True(t, ok, "summary must be a map")
- require.Equal(t, 7, m.KeyID)
- require.Equal(t, 8, m.ValueID)
- require.Equal(t, iceberg.PrimitiveTypes.String, m.KeyType)
- require.Equal(t, iceberg.PrimitiveTypes.String, m.ValueType)
+ require.Equal(t, 7, m.KeyID())
+ require.Equal(t, 8, m.ValueID())
+ require.Equal(t, iceberg.PrimitiveTypes.String, m.KeyType())
+ require.Equal(t, iceberg.PrimitiveTypes.String, m.ValueType())
}
func TestInspectSnapshots(t *testing.T) {
@@ -1148,8 +1148,8 @@ func TestInspectManifestsSchema(t *testing.T) {
require.False(t, fields[idx].Required)
}
require.True(t, fields[11].Required)
- require.True(t, fields[11].Type.(*iceberg.ListType).ElementRequired)
- require.Equal(t, 9, fields[11].Type.(*iceberg.ListType).ElementID)
+ require.True(t, fields[11].Type.(*iceberg.ListType).ElementRequired())
+ require.Equal(t, 9, fields[11].Type.(*iceberg.ListType).ElementID())
arrowSchema, err := table.SchemaToArrowSchema(sc, nil, true, false)
require.NoError(t, err)
@@ -1159,7 +1159,7 @@ func TestInspectManifestsSchema(t *testing.T) {
}
require.False(t, arrowSchema.Field(11).Nullable)
- partitionSummary :=
fields[11].Type.(*iceberg.ListType).Element.(*iceberg.StructType)
+ partitionSummary :=
fields[11].Type.(*iceberg.ListType).Element().(*iceberg.StructType)
require.Equal(t,
[]string{"contains_null", "contains_nan", "lower_bound",
"upper_bound"},
testFieldNames(iceberg.NewSchema(0,
partitionSummary.Fields()...)))
diff --git a/table/internal/parquet_files.go b/table/internal/parquet_files.go
index 95ccc7c73..b5251bfbc 100644
--- a/table/internal/parquet_files.go
+++ b/table/internal/parquet_files.go
@@ -3533,7 +3533,7 @@ func (v *id2ParquetPathVisitor) Field(field
iceberg.NestedField, res func() []id
}
func (v *id2ParquetPathVisitor) List(listType iceberg.ListType, elemResult
func() []id2ParquetPath) []id2ParquetPath {
- v.fieldID = listType.ElementID
+ v.fieldID = listType.ElementID()
v.path = append(v.path, "list")
result := elemResult()
v.path = v.path[:len(v.path)-1]
@@ -3542,12 +3542,12 @@ func (v *id2ParquetPathVisitor) List(listType
iceberg.ListType, elemResult func(
}
func (v *id2ParquetPathVisitor) Map(m iceberg.MapType, keyResult func()
[]id2ParquetPath, valResult func() []id2ParquetPath) []id2ParquetPath {
- v.fieldID = m.KeyID
+ v.fieldID = m.KeyID()
v.path = append(v.path, "key_value")
keyRes := keyResult()
v.path = v.path[:len(v.path)-1]
- v.fieldID = m.ValueID
+ v.fieldID = m.ValueID()
v.path = append(v.path, "key_value")
valRes := valResult()
v.path = v.path[:len(v.path)-1]
diff --git a/table/metadata.go b/table/metadata.go
index bd0904072..d7ab80e23 100644
--- a/table/metadata.go
+++ b/table/metadata.go
@@ -2752,7 +2752,7 @@ func cloneSchema(schema *iceberg.Schema) *iceberg.Schema {
return iceberg.NewSchemaWithIdentifiers(
schema.ID,
- slices.Clone(schema.IdentifierFieldIDs),
+ schema.IdentifierFieldIDs(),
schema.Fields()...,
)
}
diff --git a/table/metadata_builder_from_base_test.go
b/table/metadata_builder_from_base_test.go
index 52da9772a..28c1465ad 100644
--- a/table/metadata_builder_from_base_test.go
+++ b/table/metadata_builder_from_base_test.go
@@ -113,8 +113,6 @@ func TestMetadataBuilderFromBaseCopiesBuiltinMetadata(t
*testing.T) {
require.NotSame(t, &metadata.SchemaList[0], &builder.schemaList[0])
require.NotSame(t, metadata.SchemaList[0], builder.schemaList[0])
- builder.schemaList[0].IdentifierFieldIDs[0] = 99
- require.Equal(t, []int{1}, metadata.SchemaList[0].IdentifierFieldIDs)
require.NotSame(t, &metadata.Specs[0], &builder.specs[0])
require.NotSame(t, &metadata.SnapshotList[0], &builder.snapshotList[0])
diff --git a/table/metadata_getters_test.go b/table/metadata_getters_test.go
index d5acda12a..be24d83cc 100644
--- a/table/metadata_getters_test.go
+++ b/table/metadata_getters_test.go
@@ -102,7 +102,6 @@ func TestMetadataGettersReturnDefensiveCopies(t *testing.T)
{
schemas := metadata.Schemas()
schemas[0].ID = 99
- schemas[0].IdentifierFieldIDs[0] = 99
nestedFields := schemas[0].Fields()
nestedFields[0].Name = "mutated"
nestedFields[0].Type = iceberg.PrimitiveTypes.String
@@ -188,14 +187,11 @@ func TestMetadataSchemaGetterCopiesNestedValues(t
*testing.T) {
originalFields := schema.Fields()
cloned := metadata.CurrentSchema()
- cloned.IdentifierFieldIDs[0] = 99
fields := cloned.FieldsRef(iceinternal.SchemaRef{})
payload := fields[0].Type.(*iceberg.StructType)
- payload.FieldList[1].Name = "changed"
-
payload.FieldList[1].Type.(*iceberg.ListType).Element.(*iceberg.StructType).FieldList[0].InitialDefault.([]any)[0].(map[string]any)["bytes"].([]byte)[0]
= 99
-
payload.FieldList[2].Type.(*iceberg.MapType).ValueType.(*iceberg.StructType).FieldList[0].WriteDefault.(map[string]any)["values"].([]any)[0]
= "changed"
+
payload.Field(1).Type.(*iceberg.ListType).Element().(*iceberg.StructType).Field(0).InitialDefault.([]any)[0].(map[string]any)["bytes"].([]byte)[0]
= 99
+
payload.Field(2).Type.(*iceberg.MapType).ValueType().(*iceberg.StructType).Field(0).WriteDefault.(map[string]any)["values"].([]any)[0]
= "changed"
- require.Equal(t, []int{1}, schema.IdentifierFieldIDs)
require.Equal(t, originalFields, schema.Fields())
}
diff --git a/table/metadata_internal_test.go b/table/metadata_internal_test.go
index fd504a247..a419486b7 100644
--- a/table/metadata_internal_test.go
+++ b/table/metadata_internal_test.go
@@ -2718,8 +2718,8 @@ func TestParseSchemaIdentifierFields(t *testing.T) {
schemas := meta.Schemas()
require.Len(t, schemas, 2)
- require.Empty(t, schemas[0].IdentifierFieldIDs)
- require.Equal(t, []int{1, 2}, schemas[1].IdentifierFieldIDs)
+ require.Empty(t, schemas[0].IdentifierFieldIDs())
+ require.Equal(t, []int{1, 2}, schemas[1].IdentifierFieldIDs())
}
func TestInvalidSnapshotLogOrder(t *testing.T) {
diff --git a/table/reference_tables_test.go b/table/reference_tables_test.go
index 5aa19b01e..3e5a25674 100644
--- a/table/reference_tables_test.go
+++ b/table/reference_tables_test.go
@@ -149,7 +149,7 @@ func expectedReferenceRow(fields []iceberg.NestedField, raw
json.RawMessage) (st
if err := dec.Decode(&v); err != nil {
return "", err
}
- row, err := expectedReferenceValue(&iceberg.StructType{FieldList:
fields}, v)
+ row, err := expectedReferenceValue(iceberg.NewStructType(fields...), v)
if err != nil {
return "", err
}
@@ -211,8 +211,8 @@ func expectedReferenceValue(typ iceberg.Type, v any) (any,
error) {
if !ok {
return nil, fmt.Errorf("struct must be a JSON object,
got %v", v)
}
- out := make(map[string]any, len(typ.FieldList))
- for _, f := range typ.FieldList {
+ out := make(map[string]any, typ.NumFields())
+ for _, f := range typ.Fields() {
key := strconv.Itoa(f.ID)
raw, present := obj[key]
if !present {
@@ -224,7 +224,7 @@ func expectedReferenceValue(typ iceberg.Type, v any) (any,
error) {
}
out[key] = fv
}
- if len(obj) != len(typ.FieldList) {
+ if len(obj) != typ.NumFields() {
return nil, fmt.Errorf("struct %v has keys the schema
does not", obj)
}
@@ -236,7 +236,7 @@ func expectedReferenceValue(typ iceberg.Type, v any) (any,
error) {
}
out := make([]any, len(elems))
for i, e := range elems {
- ev, err := expectedReferenceValue(typ.Element, e)
+ ev, err := expectedReferenceValue(typ.Element(), e)
if err != nil {
return nil, err
}
@@ -256,11 +256,11 @@ func expectedReferenceValue(typ iceberg.Type, v any)
(any, error) {
}
pairs := make([][2]any, len(keys))
for i := range keys {
- k, err := expectedReferenceValue(typ.KeyType, keys[i])
+ k, err := expectedReferenceValue(typ.KeyType(), keys[i])
if err != nil {
return nil, err
}
- val, err := expectedReferenceValue(typ.ValueType,
values[i])
+ val, err := expectedReferenceValue(typ.ValueType(),
values[i])
if err != nil {
return nil, err
}
@@ -351,11 +351,11 @@ func arrowReferenceValue(typ iceberg.Type, arr
arrow.Array, i int) (any, error)
return a.Value(i).ToTime(dt.Unit).UnixMicro(), nil
case *iceberg.StructType:
a, ok := arr.(*array.Struct)
- if !ok || a.NumField() != len(typ.FieldList) {
+ if !ok || a.NumField() != typ.NumFields() {
return nil, fmt.Errorf("struct read as %s",
arr.DataType())
}
- out := make(map[string]any, len(typ.FieldList))
- for j, f := range typ.FieldList {
+ out := make(map[string]any, typ.NumFields())
+ for j, f := range typ.Fields() {
v, err := arrowReferenceValue(f.Type, a.Field(j), i)
if err != nil {
return nil, fmt.Errorf("field %d: %w", f.ID,
err)
@@ -372,11 +372,11 @@ func arrowReferenceValue(typ iceberg.Type, arr
arrow.Array, i int) (any, error)
start, end := a.ValueOffsets(i)
pairs := make([][2]any, 0, end-start)
for j := int(start); j < int(end); j++ {
- k, err := arrowReferenceValue(typ.KeyType, a.Keys(), j)
+ k, err := arrowReferenceValue(typ.KeyType(), a.Keys(),
j)
if err != nil {
return nil, err
}
- v, err := arrowReferenceValue(typ.ValueType, a.Items(),
j)
+ v, err := arrowReferenceValue(typ.ValueType(),
a.Items(), j)
if err != nil {
return nil, err
}
@@ -392,7 +392,7 @@ func arrowReferenceValue(typ iceberg.Type, arr arrow.Array,
i int) (any, error)
start, end := a.ValueOffsets(i)
out := make([]any, 0, end-start)
for j := int(start); j < int(end); j++ {
- v, err := arrowReferenceValue(typ.Element,
a.ListValues(), j)
+ v, err := arrowReferenceValue(typ.Element(),
a.ListValues(), j)
if err != nil {
return nil, err
}
diff --git a/table/scan_planning_remote.go b/table/scan_planning_remote.go
index ec55a8b76..8d4c02a0f 100644
--- a/table/scan_planning_remote.go
+++ b/table/scan_planning_remote.go
@@ -82,17 +82,17 @@ func appendRemoteProjectedTypeIDs(ids *[]int, typ
iceberg.Type, fieldID int, inc
appendRemoteProjectedFieldIDs(ids, field)
}
case *iceberg.ListType:
- if remoteProjectedLeaf(typ.Element) {
- *ids = append(*ids, typ.ElementID)
+ if remoteProjectedLeaf(typ.Element()) {
+ *ids = append(*ids, typ.ElementID())
} else {
- appendRemoteProjectedTypeIDs(ids, typ.Element,
typ.ElementID, false)
+ appendRemoteProjectedTypeIDs(ids, typ.Element(),
typ.ElementID(), false)
}
case *iceberg.MapType:
- if remoteProjectedLeaf(typ.ValueType) {
- *ids = append(*ids, typ.KeyID, typ.ValueID)
+ if remoteProjectedLeaf(typ.ValueType()) {
+ *ids = append(*ids, typ.KeyID(), typ.ValueID())
} else {
- appendRemoteProjectedTypeIDs(ids, typ.ValueType,
typ.ValueID, false)
- appendRemoteProjectedTypeIDs(ids, typ.KeyType,
typ.KeyID, false)
+ appendRemoteProjectedTypeIDs(ids, typ.ValueType(),
typ.ValueID(), false)
+ appendRemoteProjectedTypeIDs(ids, typ.KeyType(),
typ.KeyID(), false)
}
default:
if includeFieldID {
diff --git a/table/scanner.go b/table/scanner.go
index b5acc8532..983dae04d 100644
--- a/table/scanner.go
+++ b/table/scanner.go
@@ -914,7 +914,7 @@ func appendMissingLineageFields(s *iceberg.Schema,
lineageFields []iceberg.Neste
existing[f.ID] = struct{}{}
}
- return iceberg.NewSchemaWithIdentifiers(s.ID, s.IdentifierFieldIDs,
fields...)
+ return iceberg.NewSchemaWithIdentifiers(s.ID, s.IdentifierFieldIDs(),
fields...)
}
func buildPartitionProjection(specID int, meta Metadata, schema
*iceberg.Schema, rowFilter iceberg.BooleanExpression, caseSensitive bool)
(iceberg.BooleanExpression, error) {
diff --git a/table/scanner_internal_test.go b/table/scanner_internal_test.go
index 33008d2c8..9a86701c1 100644
--- a/table/scanner_internal_test.go
+++ b/table/scanner_internal_test.go
@@ -1024,7 +1024,7 @@ func TestAppendMissingLineageFields(t *testing.T) {
withLineage := appendMissingLineageFields(schema,
[]iceberg.NestedField{iceberg.RowID()})
- assert.Equal(t, []int{1}, schema.IdentifierFieldIDs)
+ assert.Equal(t, []int{1}, schema.IdentifierFieldIDs())
assert.Len(t, schema.Fields(), 1)
assert.Len(t, withLineage.Fields(), 2)
assert.Equal(t, iceberg.RowIDColumnName, withLineage.Fields()[1].Name)
diff --git a/table/stats_ndv_test.go b/table/stats_ndv_test.go
index 10214c9dd..561995d31 100644
--- a/table/stats_ndv_test.go
+++ b/table/stats_ndv_test.go
@@ -579,11 +579,9 @@ func TestComputeNDVsSkipsNullValues(t *testing.T) {
func TestComputeNDVsRejectsNonPrimitiveColumns(t *testing.T) {
sc := iceberg.NewSchema(0,
iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
- iceberg.NestedField{ID: 2, Name: "s", Required: true, Type:
&iceberg.StructType{
- FieldList: []iceberg.NestedField{
- {ID: 3, Name: "a", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
- },
- }},
+ iceberg.NestedField{ID: 2, Name: "s", Required: true, Type:
iceberg.NewStructType(
+ iceberg.NestedField{ID: 3, Name: "a", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ )},
)
tbl, ctx := createNDVTable(t, "ndv_nested", sc, []string{
`{"id": 1, "s": {"a": 10}}`,
diff --git a/table/update_schema.go b/table/update_schema.go
index cad5d38ea..da2add9ea 100644
--- a/table/update_schema.go
+++ b/table/update_schema.go
@@ -215,7 +215,7 @@ func (u *UpdateSchema) initIdentifierFieldNames() error {
}
identifierFieldNames := make(map[string]struct{})
- for _, id := range u.schema.IdentifierFieldIDs {
+ for _, id := range u.schema.IdentifierFieldIDs() {
name, ok := u.schema.FindColumnName(id)
if !ok {
return fmt.Errorf("identifier field %d not found", id)
@@ -796,7 +796,7 @@ func (u *UpdateSchema) unionField(path []string, newField
iceberg.NestedField) e
if !ok {
return fmt.Errorf("cannot change field to map: %s",
strings.Join(path, "."))
}
- if !isIgnorableTypeUpdate(existingMap.KeyType, t.KeyType) {
+ if !isIgnorableTypeUpdate(existingMap.KeyType(), t.KeyType()) {
return fmt.Errorf("cannot update map key: %s",
strings.Join(childPath(path, "key"), "."))
}
if err := u.unionField(childPath(path, "value"),
t.ValueField()); err != nil {
@@ -1438,11 +1438,11 @@ func (a *applyChanges) List(listType iceberg.ListType,
elementResult iceberg.Typ
panic(fmt.Sprintf("cannot delete element type from list: %s",
elementResult))
}
- return iceberg.NewListType(listType.ElementID, elementType,
a.updatedRequired(listType.ElementID, listType.ElementRequired))
+ return iceberg.NewListType(listType.ElementID(), elementType,
a.updatedRequired(listType.ElementID(), listType.ElementRequired()))
}
func (a *applyChanges) Map(mapType iceberg.MapType, keyResult, valueResult
iceberg.Type) iceberg.Type {
- keyID := mapType.KeyID
+ keyID := mapType.KeyID()
if _, ok := a.deletes[keyID]; ok {
panic(fmt.Errorf("cannot delete map keys: %s",
mapType.String()))
}
@@ -1455,7 +1455,7 @@ func (a *applyChanges) Map(mapType iceberg.MapType,
keyResult, valueResult icebe
panic(fmt.Errorf("cannot add fields to map keys: %s",
mapType.String()))
}
- if !mapType.KeyType.Equals(keyResult) {
+ if !mapType.KeyType().Equals(keyResult) {
panic(fmt.Errorf("cannot alter map keys: %s", mapType.String()))
}
@@ -1466,7 +1466,7 @@ func (a *applyChanges) Map(mapType iceberg.MapType,
keyResult, valueResult icebe
panic(fmt.Errorf("cannot delete value type from map: %s",
mapType.String()))
}
- return iceberg.NewMapType(mapType.KeyID, mapType.KeyType,
mapType.ValueID, valueType, a.updatedRequired(mapType.ValueID,
mapType.ValueRequired))
+ return iceberg.NewMapType(mapType.KeyID(), mapType.KeyType(),
mapType.ValueID(), valueType, a.updatedRequired(mapType.ValueID(),
mapType.ValueRequired()))
}
func (a *applyChanges) Primitive(primitive iceberg.PrimitiveType) iceberg.Type
{
diff --git a/table/update_schema_test.go b/table/update_schema_test.go
index 9ef9524f1..b9d752706 100644
--- a/table/update_schema_test.go
+++ b/table/update_schema_test.go
@@ -1079,9 +1079,9 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has identifier field IDs set
- assert.Len(t, newSchema.IdentifierFieldIDs, 1)
- if len(newSchema.IdentifierFieldIDs) > 0 {
- assert.Equal(t, 1, newSchema.IdentifierFieldIDs[0]) //
id field has ID 1
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 1)
+ if len(newSchema.IdentifierFieldIDs()) > 0 {
+ assert.Equal(t, 1, newSchema.IdentifierFieldIDs()[0])
// id field has ID 1
}
})
@@ -1094,9 +1094,9 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has identifier field IDs set
- assert.Len(t, newSchema.IdentifierFieldIDs, 2)
- assert.Contains(t, newSchema.IdentifierFieldIDs, 1) // id field
- assert.Contains(t, newSchema.IdentifierFieldIDs, 2) // name
field
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 2)
+ assert.Contains(t, newSchema.IdentifierFieldIDs(), 1) // id
field
+ assert.Contains(t, newSchema.IdentifierFieldIDs(), 2) // name
field
})
t.Run("test set identifier field with case sensitive matching", func(t
*testing.T) {
@@ -1117,8 +1117,8 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has identifier field IDs set
- assert.Len(t, newSchema.IdentifierFieldIDs, 1)
- assert.Equal(t, 1, newSchema.IdentifierFieldIDs[0]) // id field
(case insensitive match)
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 1)
+ assert.Equal(t, 1, newSchema.IdentifierFieldIDs()[0]) // id
field (case insensitive match)
})
t.Run("test set identifier field with non-existent field", func(t
*testing.T) {
@@ -1139,7 +1139,7 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has no identifier field IDs
- assert.Len(t, newSchema.IdentifierFieldIDs, 0)
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 0)
})
t.Run("test set identifier field chained with other operations", func(t
*testing.T) {
@@ -1154,9 +1154,9 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has identifier field IDs set
- assert.Len(t, newSchema.IdentifierFieldIDs, 2)
- assert.Contains(t, newSchema.IdentifierFieldIDs, 1) // id field
- assert.Contains(t, newSchema.IdentifierFieldIDs, 12) // email
field (newly added)
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 2)
+ assert.Contains(t, newSchema.IdentifierFieldIDs(), 1) // id
field
+ assert.Contains(t, newSchema.IdentifierFieldIDs(), 12) // email
field (newly added)
})
t.Run("test set identifier field with duplicate field paths", func(t
*testing.T) {
@@ -1168,8 +1168,8 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that the schema has identifier field IDs set
(duplicates should be deduplicated)
- assert.Len(t, newSchema.IdentifierFieldIDs, 1)
- assert.Equal(t, 1, newSchema.IdentifierFieldIDs[0]) // id field
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 1)
+ assert.Equal(t, 1, newSchema.IdentifierFieldIDs()[0]) // id
field
})
t.Run("test set identifier field replaces existing identifier fields",
func(t *testing.T) {
@@ -1189,8 +1189,8 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that only name is now an identifier field
- assert.Len(t, newSchema.IdentifierFieldIDs, 1)
- assert.Equal(t, 2, newSchema.IdentifierFieldIDs[0]) // name
field has ID 2
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 1)
+ assert.Equal(t, 2, newSchema.IdentifierFieldIDs()[0]) // name
field has ID 2
})
t.Run("test set identifier field multiple times", func(t *testing.T) {
@@ -1206,8 +1206,8 @@ func TestSetIdentifierField(t *testing.T) {
assert.NotNil(t, newSchema)
// Check that only the last SetIdentifierField call is applied
- assert.Len(t, newSchema.IdentifierFieldIDs, 1)
- assert.Equal(t, 2, newSchema.IdentifierFieldIDs[0]) // name
field has ID 2
+ assert.Len(t, newSchema.IdentifierFieldIDs(), 1)
+ assert.Equal(t, 2, newSchema.IdentifierFieldIDs()[0]) // name
field has ID 2
})
t.Run("test rename then set identifier to old name fails", func(t
*testing.T) {
@@ -1233,9 +1233,9 @@ func TestSetIdentifierField(t *testing.T) {
require.NoError(t, err)
require.NotNil(t, newSchema)
- require.Len(t, newSchema.IdentifierFieldIDs, 1)
+ require.Len(t, newSchema.IdentifierFieldIDs(), 1)
// Renamed field keeps ID 1
- assert.Equal(t, 1, newSchema.IdentifierFieldIDs[0])
+ assert.Equal(t, 1, newSchema.IdentifierFieldIDs()[0])
field, ok := newSchema.FindColumnName(1)
require.True(t, ok)
assert.Equal(t, "new_id", field)
@@ -1319,7 +1319,7 @@ func TestDeleteIdentifierColumn(t *testing.T) {
SetIdentifierField([][]string{}).
Apply()
require.NoError(t, err)
- assert.Empty(t, newSchema.IdentifierFieldIDs)
+ assert.Empty(t, newSchema.IdentifierFieldIDs())
_, found := newSchema.FindFieldByName("id")
assert.False(t, found)
})
@@ -1330,7 +1330,7 @@ func TestDeleteIdentifierColumn(t *testing.T) {
DeleteColumn([]string{"id"}).
Apply()
require.NoError(t, err)
- assert.Equal(t, []int{2}, newSchema.IdentifierFieldIDs)
+ assert.Equal(t, []int{2}, newSchema.IdentifierFieldIDs())
})
}
@@ -1349,7 +1349,7 @@ func TestSetIdentifierFieldDeterministicOrder(t
*testing.T) {
require.NoError(t, err)
require.NotNil(t, newSchema)
- assert.Equal(t, []int{1, 2, 3},
newSchema.IdentifierFieldIDs)
+ assert.Equal(t, []int{1, 2, 3},
newSchema.IdentifierFieldIDs())
// Every independently-produced schema must compare
equal, which is
// exactly the invariant the ordering bug breaks.
@@ -1614,7 +1614,7 @@ func TestApplyChangesListElementOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "tags field must be present in the applied
schema")
listType, ok := tags.Type.(*iceberg.ListType)
require.True(t, ok, "tags must remain a ListType after apply")
- assert.False(t, listType.ElementRequired,
+ assert.False(t, listType.ElementRequired(),
"list element optionality update must be reflected in
the applied schema")
})
@@ -1633,7 +1633,7 @@ func TestApplyChangesListElementOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "tags field must be present in the applied
schema")
listType, ok := tags.Type.(*iceberg.ListType)
require.True(t, ok, "tags must remain a ListType after apply")
- assert.True(t, listType.ElementRequired,
+ assert.True(t, listType.ElementRequired(),
"list element optionality update must be reflected in
the applied schema")
})
@@ -1666,9 +1666,9 @@ func TestApplyChangesListElementOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "tags field must be present in the applied
schema")
listType, ok := tags.Type.(*iceberg.ListType)
require.True(t, ok, "tags must remain a ListType after apply")
- assert.True(t,
iceberg.PrimitiveTypes.Int64.Equals(listType.Element),
+ assert.True(t,
iceberg.PrimitiveTypes.Int64.Equals(listType.Element()),
"type promotion must still be applied alongside
optionality change")
- assert.False(t, listType.ElementRequired,
+ assert.False(t, listType.ElementRequired(),
"optionality change must be applied alongside type
promotion")
})
@@ -1687,7 +1687,7 @@ func TestApplyChangesListElementOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "tags field must be present in the applied
schema")
listType, ok := tags.Type.(*iceberg.ListType)
require.True(t, ok, "tags must remain a ListType after apply")
- assert.True(t, listType.ElementRequired,
+ assert.True(t, listType.ElementRequired(),
"ElementRequired must be preserved from the original
schema when no Required update is registered")
})
@@ -1706,7 +1706,7 @@ func TestApplyChangesListElementOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "tags field must be present in the applied
schema")
listType, ok := tags.Type.(*iceberg.ListType)
require.True(t, ok, "tags must remain a ListType after apply")
- assert.True(t, listType.ElementRequired,
+ assert.True(t, listType.ElementRequired(),
"ElementRequired must be preserved when the registered
update leaves Required unset")
})
}
@@ -1734,7 +1734,7 @@ func TestApplyChangesMapValueOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "properties field must be present in the
applied schema")
mapType, ok := props.Type.(*iceberg.MapType)
require.True(t, ok, "properties must remain a MapType after
apply")
- assert.False(t, mapType.ValueRequired,
+ assert.False(t, mapType.ValueRequired(),
"map value optionality update must be reflected in the
applied schema")
})
@@ -1753,7 +1753,7 @@ func TestApplyChangesMapValueOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "properties field must be present in the
applied schema")
mapType, ok := props.Type.(*iceberg.MapType)
require.True(t, ok, "properties must remain a MapType after
apply")
- assert.True(t, mapType.ValueRequired,
+ assert.True(t, mapType.ValueRequired(),
"map value optionality update must be reflected in the
applied schema")
})
@@ -1786,9 +1786,9 @@ func TestApplyChangesMapValueOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "properties field must be present in the
applied schema")
mapType, ok := props.Type.(*iceberg.MapType)
require.True(t, ok, "properties must remain a MapType after
apply")
- assert.True(t,
iceberg.PrimitiveTypes.Int64.Equals(mapType.ValueType),
+ assert.True(t,
iceberg.PrimitiveTypes.Int64.Equals(mapType.ValueType()),
"type promotion must still be applied alongside
optionality change")
- assert.False(t, mapType.ValueRequired,
+ assert.False(t, mapType.ValueRequired(),
"optionality change must be applied alongside type
promotion")
})
@@ -1807,7 +1807,7 @@ func TestApplyChangesMapValueOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "properties field must be present in the
applied schema")
mapType, ok := props.Type.(*iceberg.MapType)
require.True(t, ok, "properties must remain a MapType after
apply")
- assert.True(t, mapType.ValueRequired,
+ assert.True(t, mapType.ValueRequired(),
"ValueRequired must be preserved from the original
schema when no Required update is registered")
})
@@ -1826,7 +1826,7 @@ func TestApplyChangesMapValueOptionalityUpdates(t
*testing.T) {
require.True(t, ok, "properties field must be present in the
applied schema")
mapType, ok := props.Type.(*iceberg.MapType)
require.True(t, ok, "properties must remain a MapType after
apply")
- assert.True(t, mapType.ValueRequired,
+ assert.True(t, mapType.ValueRequired(),
"ValueRequired must be preserved when the registered
update leaves Required unset")
})
}
diff --git a/table/variant_residual.go b/table/variant_residual.go
index 6e3a8e36f..49f2e7a98 100644
--- a/table/variant_residual.go
+++ b/table/variant_residual.go
@@ -46,7 +46,7 @@ func augmentSchemaWithExtracts(fileSchema *iceberg.Schema,
cols []iceberg.Varian
})
}
- return iceberg.NewSchemaWithIdentifiers(fileSchema.ID,
fileSchema.IdentifierFieldIDs, fields...)
+ return iceberg.NewSchemaWithIdentifiers(fileSchema.ID,
fileSchema.IdentifierFieldIDs(), fields...)
}
// buildExtractColumn materializes one variant extract term into a typed Arrow
array over rec,
diff --git a/types.go b/types.go
index 5440fa40c..2e3da7182 100644
--- a/types.go
+++ b/types.go
@@ -467,15 +467,17 @@ func (n *NestedField) UnmarshalJSON(b []byte) error {
return nil
}
+// StructType is a struct type. Build one with NewStructType and read its
+// fields with NumFields, Field or Fields.
type StructType struct {
- FieldList []NestedField `json:"fields"`
+ fields []NestedField
}
// NewStructType returns a struct type with the given fields. The fields are
// copied, so later changes to a slice passed with fields... do not affect the
// returned type.
func NewStructType(fields ...NestedField) *StructType {
- return &StructType{FieldList: slices.Clone(fields)}
+ return &StructType{fields: slices.Clone(fields)}
}
func (s *StructType) Equals(other Type) bool {
@@ -484,28 +486,30 @@ func (s *StructType) Equals(other Type) bool {
return false
}
- return slices.EqualFunc(s.FieldList, st.FieldList, func(a, b
NestedField) bool {
+ return slices.EqualFunc(s.fields, st.fields, func(a, b NestedField)
bool {
return a.Equals(b)
})
}
// NumFields returns the number of fields in the struct.
-func (s *StructType) NumFields() int { return len(s.FieldList) }
+func (s *StructType) NumFields() int { return len(s.fields) }
// Field returns the i-th field of the struct. It panics if i is out of range.
-func (s *StructType) Field(i int) NestedField { return s.FieldList[i] }
+func (s *StructType) Field(i int) NestedField { return s.fields[i] }
// Fields returns a copy of the struct's fields. Changing the returned slice
// does not change the struct. Use NumFields and Field to read the fields
// without copying them.
-func (s *StructType) Fields() []NestedField { return slices.Clone(s.FieldList)
}
+func (s *StructType) Fields() []NestedField { return slices.Clone(s.fields) }
// The JSON methods of the nested types name every serialized field instead of
// encoding through an alias of the type, so the wire format does not depend on
// which Go fields are exported.
-func (s *StructType) MarshalJSON() ([]byte, error) {
- fields := s.FieldList
+// MarshalJSON has a value receiver on purpose: [Schema.AsStruct] returns a
+// StructType value, which must not encode as {}.
+func (s StructType) MarshalJSON() ([]byte, error) {
+ fields := s.fields
if fields == nil {
fields = []NestedField{}
}
@@ -527,7 +531,7 @@ func (s *StructType) UnmarshalJSON(b []byte) error {
return fmt.Errorf("%w: struct is missing required 'fields'
array in JSON", ErrInvalidSchema)
}
- s.FieldList = *aux.Fields
+ s.fields = *aux.Fields
return nil
}
@@ -536,7 +540,7 @@ func (*StructType) Type() string { return "struct" }
func (s *StructType) String() string {
var b strings.Builder
b.WriteString("struct<")
- for i, f := range s.FieldList {
+ for i, f := range s.fields {
if i != 0 {
b.WriteString(", ")
}
@@ -559,27 +563,39 @@ func (s *StructType) String() string {
return b.String()
}
+// ListType is a list type. Build one with NewListType.
type ListType struct {
- ElementID int `json:"element-id"`
- Element Type `json:"-"`
- ElementRequired bool `json:"element-required"`
+ elementID int
+ element Type
+ elementRequired bool
}
// NewListType returns a list type whose element field has the given ID, type
// and required flag.
func NewListType(elementID int, element Type, required bool) *ListType {
- return &ListType{ElementID: elementID, Element: element,
ElementRequired: required}
+ return &ListType{elementID: elementID, element: element,
elementRequired: required}
}
-func (l *ListType) MarshalJSON() ([]byte, error) {
+// ElementID returns the field ID of the list's element.
+func (l *ListType) ElementID() int { return l.elementID }
+
+// Element returns the type of the list's element.
+func (l *ListType) Element() Type { return l.element }
+
+// ElementRequired reports whether the list's elements are required.
+func (l *ListType) ElementRequired() bool { return l.elementRequired }
+
+// MarshalJSON has a value receiver on purpose: a ListType value, such as one
+// held in a map, must not encode as {}.
+func (l ListType) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
ElementID int `json:"element-id"`
ElementRequired bool `json:"element-required"`
Element *typeIFace `json:"element"`
}{
- Type: l.Type(), ElementID: l.ElementID, ElementRequired:
l.ElementRequired,
- Element: &typeIFace{l.Element},
+ Type: l.Type(), ElementID: l.elementID, ElementRequired:
l.elementRequired,
+ Element: &typeIFace{l.element},
})
}
@@ -589,9 +605,9 @@ func (l *ListType) Equals(other Type) bool {
return false
}
- return l.ElementID == rhs.ElementID &&
- l.Element.Equals(rhs.Element) &&
- l.ElementRequired == rhs.ElementRequired
+ return l.elementID == rhs.elementID &&
+ l.element.Equals(rhs.element) &&
+ l.elementRequired == rhs.elementRequired
}
func (l *ListType) Fields() []NestedField {
@@ -600,15 +616,15 @@ func (l *ListType) Fields() []NestedField {
func (l *ListType) ElementField() NestedField {
return NestedField{
- ID: l.ElementID,
+ ID: l.elementID,
Name: "element",
- Type: l.Element,
- Required: l.ElementRequired,
+ Type: l.element,
+ Required: l.elementRequired,
}
}
func (*ListType) Type() string { return "list" }
-func (l *ListType) String() string { return fmt.Sprintf("list<%s>", l.Element)
}
+func (l *ListType) String() string { return fmt.Sprintf("list<%s>", l.element)
}
func (l *ListType) UnmarshalJSON(b []byte) error {
aux := struct {
@@ -630,31 +646,49 @@ func (l *ListType) UnmarshalJSON(b []byte) error {
return fmt.Errorf("%w: field is missing required
'element-required' key in JSON", ErrInvalidSchema)
}
- l.ElementID = *aux.ID
- l.Element = aux.Elem.Type
- l.ElementRequired = *aux.Req
+ l.elementID = *aux.ID
+ l.element = aux.Elem.Type
+ l.elementRequired = *aux.Req
return nil
}
+// MapType is a map type. Build one with NewMapType.
type MapType struct {
- KeyID int `json:"key-id"`
- KeyType Type `json:"-"`
- ValueID int `json:"value-id"`
- ValueType Type `json:"-"`
- ValueRequired bool `json:"value-required"`
+ keyID int
+ keyType Type
+ valueID int
+ valueType Type
+ valueRequired bool
}
// NewMapType returns a map type with the given key and value fields. Map keys
// are always required.
func NewMapType(keyID int, key Type, valueID int, value Type, valueRequired
bool) *MapType {
return &MapType{
- KeyID: keyID, KeyType: key,
- ValueID: valueID, ValueType: value, ValueRequired:
valueRequired,
+ keyID: keyID, keyType: key,
+ valueID: valueID, valueType: value, valueRequired:
valueRequired,
}
}
-func (m *MapType) MarshalJSON() ([]byte, error) {
+// KeyID returns the field ID of the map's key.
+func (m *MapType) KeyID() int { return m.keyID }
+
+// KeyType returns the type of the map's key.
+func (m *MapType) KeyType() Type { return m.keyType }
+
+// ValueID returns the field ID of the map's value.
+func (m *MapType) ValueID() int { return m.valueID }
+
+// ValueType returns the type of the map's value.
+func (m *MapType) ValueType() Type { return m.valueType }
+
+// ValueRequired reports whether the map's values are required.
+func (m *MapType) ValueRequired() bool { return m.valueRequired }
+
+// MarshalJSON has a value receiver on purpose: a MapType value, such as one
+// held in a map, must not encode as {}.
+func (m MapType) MarshalJSON() ([]byte, error) {
return json.Marshal(struct {
Type string `json:"type"`
KeyID int `json:"key-id"`
@@ -663,9 +697,9 @@ func (m *MapType) MarshalJSON() ([]byte, error) {
KeyType *typeIFace `json:"key"`
ValueType *typeIFace `json:"value"`
}{
- Type: m.Type(), KeyID: m.KeyID, ValueID: m.ValueID,
ValueRequired: m.ValueRequired,
- KeyType: &typeIFace{m.KeyType},
- ValueType: &typeIFace{m.ValueType},
+ Type: m.Type(), KeyID: m.keyID, ValueID: m.valueID,
ValueRequired: m.valueRequired,
+ KeyType: &typeIFace{m.keyType},
+ ValueType: &typeIFace{m.valueType},
})
}
@@ -675,11 +709,11 @@ func (m *MapType) Equals(other Type) bool {
return false
}
- return m.KeyID == rhs.KeyID &&
- m.KeyType.Equals(rhs.KeyType) &&
- m.ValueID == rhs.ValueID &&
- m.ValueType.Equals(rhs.ValueType) &&
- m.ValueRequired == rhs.ValueRequired
+ return m.keyID == rhs.keyID &&
+ m.keyType.Equals(rhs.keyType) &&
+ m.valueID == rhs.valueID &&
+ m.valueType.Equals(rhs.valueType) &&
+ m.valueRequired == rhs.valueRequired
}
func (m *MapType) Fields() []NestedField {
@@ -689,8 +723,8 @@ func (m *MapType) Fields() []NestedField {
func (m *MapType) KeyField() NestedField {
return NestedField{
Name: "key",
- ID: m.KeyID,
- Type: m.KeyType,
+ ID: m.keyID,
+ Type: m.keyType,
Required: true,
}
}
@@ -698,15 +732,15 @@ func (m *MapType) KeyField() NestedField {
func (m *MapType) ValueField() NestedField {
return NestedField{
Name: "value",
- ID: m.ValueID,
- Type: m.ValueType,
- Required: m.ValueRequired,
+ ID: m.valueID,
+ Type: m.valueType,
+ Required: m.valueRequired,
}
}
func (*MapType) Type() string { return "map" }
func (m *MapType) String() string {
- return fmt.Sprintf("map<%s, %s>", m.KeyType, m.ValueType)
+ return fmt.Sprintf("map<%s, %s>", m.keyType, m.valueType)
}
func (m *MapType) UnmarshalJSON(b []byte) error {
@@ -738,9 +772,9 @@ func (m *MapType) UnmarshalJSON(b []byte) error {
return fmt.Errorf("%w: field is missing required
'value-required' key in JSON", ErrInvalidSchema)
}
- m.KeyID, m.KeyType = *aux.KeyID, aux.Key.Type
- m.ValueID, m.ValueType = *aux.ValueID, aux.Value.Type
- m.ValueRequired = *aux.ValueReq
+ m.keyID, m.keyType = *aux.KeyID, aux.Key.Type
+ m.valueID, m.valueType = *aux.ValueID, aux.Value.Type
+ m.valueRequired = *aux.ValueReq
return nil
}
diff --git a/types_internal_test.go b/types_internal_test.go
new file mode 100644
index 000000000..b5122be23
--- /dev/null
+++ b/types_internal_test.go
@@ -0,0 +1,64 @@
+// 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 iceberg
+
+import (
+ "encoding/json"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+// TestNestedTypeConstructorsMatchLiterals pins that each constructor builds
the
+// same value, with the same JSON, as the composite literal it replaces.
+func TestNestedTypeConstructorsMatchLiterals(t *testing.T) {
+ fields := []NestedField{
+ {ID: 1, Name: "a", Type: PrimitiveTypes.Int32, Required: true},
+ {ID: 2, Name: "b", Type: PrimitiveTypes.String},
+ }
+
+ tests := []struct {
+ name string
+ constructed Type
+ literal Type
+ }{
+ {"struct", NewStructType(fields...), &StructType{fields:
fields}},
+ {"empty struct", NewStructType(), &StructType{}},
+ {"empty non-nil struct", NewStructType([]NestedField{}...),
&StructType{fields: []NestedField{}}},
+ {"list", NewListType(3, PrimitiveTypes.Int64, true),
&ListType{elementID: 3, element: PrimitiveTypes.Int64, elementRequired: true}},
+ {
+ "map",
+ NewMapType(4, PrimitiveTypes.String, 5,
PrimitiveTypes.Float64, false),
+ &MapType{keyID: 4, keyType: PrimitiveTypes.String,
valueID: 5, valueType: PrimitiveTypes.Float64, valueRequired: false},
+ },
+ }
+
+ for _, tt := range tests {
+ t.Run(tt.name, func(t *testing.T) {
+ assert.Equal(t, tt.literal, tt.constructed)
+ assert.True(t, tt.constructed.Equals(tt.literal))
+
+ want, err := json.Marshal(tt.literal)
+ require.NoError(t, err)
+ got, err := json.Marshal(tt.constructed)
+ require.NoError(t, err)
+ assert.JSONEq(t, string(want), string(got))
+ })
+ }
+}
diff --git a/types_test.go b/types_test.go
index 896eea9c9..659a9d000 100644
--- a/types_test.go
+++ b/types_test.go
@@ -225,22 +225,20 @@ func TestStructTypeUnmarshalRequiresFields(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- typ := &iceberg.StructType{
- FieldList: []iceberg.NestedField{
- {ID: 1, Name: "existing", Type:
iceberg.PrimitiveTypes.String, Required: true},
- },
- }
+ typ := iceberg.NewStructType(
+ iceberg.NestedField{ID: 1, Name: "existing",
Type: iceberg.PrimitiveTypes.String, Required: true},
+ )
err := json.Unmarshal([]byte(tt.data), typ)
require.ErrorIs(t, err, iceberg.ErrInvalidSchema)
assert.ErrorContains(t, err, "fields")
- assert.Len(t, typ.FieldList, 1)
+ assert.Equal(t, 1, typ.NumFields())
})
}
var empty iceberg.StructType
require.NoError(t,
json.Unmarshal([]byte(`{"type":"struct","fields":[]}`), &empty))
- assert.NotNil(t, empty.FieldList)
- assert.Empty(t, empty.FieldList)
+ assert.NotNil(t, empty.Fields())
+ assert.Empty(t, empty.Fields())
}
func TestStructTypeEmptyFieldsJSON(t *testing.T) {
@@ -251,8 +249,53 @@ func TestStructTypeEmptyFieldsJSON(t *testing.T) {
var decoded iceberg.StructType
require.NoError(t, json.Unmarshal(out, &decoded))
- assert.NotNil(t, decoded.FieldList)
- assert.Empty(t, decoded.FieldList)
+ assert.NotNil(t, decoded.Fields())
+ assert.Empty(t, decoded.Fields())
+}
+
+func TestNestedTypeValuesMarshalLikePointers(t *testing.T) {
+ schema := iceberg.NewSchema(1,
+ iceberg.NestedField{ID: 1, Name: "id", Type:
iceberg.PrimitiveTypes.Int64, Required: true},
+ )
+ list := iceberg.NewListType(2, iceberg.PrimitiveTypes.String, true)
+ mapType := iceberg.NewMapType(3, iceberg.PrimitiveTypes.String, 4,
iceberg.PrimitiveTypes.Int32, false)
+ asStruct := schema.AsStruct()
+
+ roundTrip := func(t *testing.T, value any, ptr iceberg.Type, decoded
iceberg.Type) {
+ t.Helper()
+ got, err := json.Marshal(value)
+ require.NoError(t, err)
+ want, err := json.Marshal(ptr)
+ require.NoError(t, err)
+ assert.JSONEq(t, string(want), string(got))
+ require.NoError(t, json.Unmarshal(got, decoded))
+ assert.True(t, ptr.Equals(decoded))
+ }
+
+ t.Run("struct", func(t *testing.T) {
+ roundTrip(t, asStruct, &asStruct, &iceberg.StructType{})
+ })
+ t.Run("list", func(t *testing.T) {
+ roundTrip(t, *list, list, &iceberg.ListType{})
+ })
+ t.Run("map", func(t *testing.T) {
+ roundTrip(t, *mapType, mapType, &iceberg.MapType{})
+ })
+ t.Run("map-held values", func(t *testing.T) {
+ got, err := json.Marshal(map[string]any{"s": asStruct, "l":
*list, "m": *mapType})
+ require.NoError(t, err)
+ want, err := json.Marshal(map[string]any{"s": &asStruct, "l":
list, "m": mapType})
+ require.NoError(t, err)
+ assert.JSONEq(t, string(want), string(got))
+
+ // Values in a typed map are not addressable, so only value
receivers
+ // reach them.
+ got, err = json.Marshal(map[string]iceberg.StructType{"s":
asStruct})
+ require.NoError(t, err)
+ want, err = json.Marshal(map[string]*iceberg.StructType{"s":
&asStruct})
+ require.NoError(t, err)
+ assert.JSONEq(t, string(want), string(got))
+ })
}
func TestNestedStructUnmarshalRequiresFields(t *testing.T) {
@@ -423,44 +466,6 @@ func TestStructTypeUnmarshalErrorLeavesTypeUnchanged(t
*testing.T) {
assert.Equal(t, kept(), typ)
}
-// TestNestedTypeConstructorsMatchLiterals pins that each constructor builds
the
-// same value, with the same JSON, as the composite literal it replaces.
-func TestNestedTypeConstructorsMatchLiterals(t *testing.T) {
- fields := []iceberg.NestedField{
- {ID: 1, Name: "a", Type: iceberg.PrimitiveTypes.Int32,
Required: true},
- {ID: 2, Name: "b", Type: iceberg.PrimitiveTypes.String},
- }
-
- tests := []struct {
- name string
- constructed iceberg.Type
- literal iceberg.Type
- }{
- {"struct", iceberg.NewStructType(fields...),
&iceberg.StructType{FieldList: fields}},
- {"empty struct", iceberg.NewStructType(),
&iceberg.StructType{}},
- {"empty non-nil struct",
iceberg.NewStructType([]iceberg.NestedField{}...),
&iceberg.StructType{FieldList: []iceberg.NestedField{}}},
- {"list", iceberg.NewListType(3, iceberg.PrimitiveTypes.Int64,
true), &iceberg.ListType{ElementID: 3, Element: iceberg.PrimitiveTypes.Int64,
ElementRequired: true}},
- {
- "map",
- iceberg.NewMapType(4, iceberg.PrimitiveTypes.String, 5,
iceberg.PrimitiveTypes.Float64, false),
- &iceberg.MapType{KeyID: 4, KeyType:
iceberg.PrimitiveTypes.String, ValueID: 5, ValueType:
iceberg.PrimitiveTypes.Float64, ValueRequired: false},
- },
- }
-
- for _, tt := range tests {
- t.Run(tt.name, func(t *testing.T) {
- assert.Equal(t, tt.literal, tt.constructed)
- assert.True(t, tt.constructed.Equals(tt.literal))
-
- want, err := json.Marshal(tt.literal)
- require.NoError(t, err)
- got, err := json.Marshal(tt.constructed)
- require.NoError(t, err)
- assert.JSONEq(t, string(want), string(got))
- })
- }
-}
-
func TestNewStructTypeCopiesFields(t *testing.T) {
fields := []iceberg.NestedField{
{ID: 1, Name: "a", Type: iceberg.PrimitiveTypes.Int32},
@@ -495,7 +500,10 @@ func TestStructTypeFieldAccessors(t *testing.T) {
require.Equal(t, 2, st.NumFields())
assert.Equal(t, "a", st.Field(0).Name)
assert.Equal(t, 2, st.Field(1).ID)
- assert.Equal(t, st.FieldList, st.Fields())
+ assert.Equal(t, []iceberg.NestedField{
+ {ID: 1, Name: "a", Type: iceberg.PrimitiveTypes.Int32},
+ {ID: 2, Name: "b", Type: iceberg.PrimitiveTypes.String},
+ }, st.Fields())
assert.Zero(t, iceberg.NewStructType().NumFields())
assert.Panics(t, func() { st.Field(2) })
}
@@ -608,8 +616,8 @@ func TestUnknownTypeInNestedStructs(t *testing.T) {
require.True(t, found)
arrType, ok := arrField.Type.(*iceberg.ListType)
require.True(t, ok)
- assert.IsType(t, iceberg.UnknownType{}, arrType.Element)
- assert.False(t, arrType.ElementRequired)
+ assert.IsType(t, iceberg.UnknownType{}, arrType.Element())
+ assert.False(t, arrType.ElementRequired())
// Test list type JSON serialization
listOut, err := json.Marshal(listType)
@@ -617,7 +625,7 @@ func TestUnknownTypeInNestedStructs(t *testing.T) {
var actualListType iceberg.ListType
require.NoError(t, json.Unmarshal(listOut, &actualListType))
assert.True(t, listType.Equals(&actualListType))
- assert.IsType(t, iceberg.UnknownType{}, actualListType.Element)
+ assert.IsType(t, iceberg.UnknownType{}, actualListType.Element())
// Test UnknownType in nested struct
structField, found := actual.FindFieldByName("struct")
@@ -649,8 +657,8 @@ func TestUnknownTypeInNestedStructs(t *testing.T) {
require.Equal(t, 7, innerMap.ID)
nestedMapType, ok := innerMap.Type.(*iceberg.MapType)
require.True(t, ok)
- assert.IsType(t, iceberg.UnknownType{}, nestedMapType.ValueType)
- assert.False(t, nestedMapType.ValueRequired)
+ assert.IsType(t, iceberg.UnknownType{}, nestedMapType.ValueType())
+ assert.False(t, nestedMapType.ValueRequired())
// Test deep nesting: UnknownType in struct within struct
var structArr iceberg.NestedField
@@ -681,8 +689,8 @@ func TestUnknownTypeInNestedStructs(t *testing.T) {
require.True(t, found)
actualMapType, ok := mapField.Type.(*iceberg.MapType)
require.True(t, ok)
- assert.IsType(t, iceberg.UnknownType{}, actualMapType.ValueType)
- assert.False(t, actualMapType.ValueRequired)
+ assert.IsType(t, iceberg.UnknownType{}, actualMapType.ValueType())
+ assert.False(t, actualMapType.ValueRequired())
// Test map type JSON serialization
mapOut, err := json.Marshal(standaloneMapType)
@@ -690,7 +698,7 @@ func TestUnknownTypeInNestedStructs(t *testing.T) {
var actualMapType2 iceberg.MapType
require.NoError(t, json.Unmarshal(mapOut, &actualMapType2))
assert.True(t, standaloneMapType.Equals(&actualMapType2))
- assert.IsType(t, iceberg.UnknownType{}, actualMapType2.ValueType)
+ assert.IsType(t, iceberg.UnknownType{}, actualMapType2.ValueType())
}
func TestUnknownTypeEquality(t *testing.T) {
@@ -754,12 +762,12 @@ func TestVariantInNestedTypes(t *testing.T) {
listField := out.Field(0)
listType, ok := listField.Type.(*iceberg.ListType)
require.True(t, ok)
- assert.True(t, listType.Element.Equals(iceberg.VariantType{}))
+ assert.True(t, listType.Element().Equals(iceberg.VariantType{}))
mapField := out.Field(1)
mapType, ok := mapField.Type.(*iceberg.MapType)
require.True(t, ok)
- assert.True(t, mapType.ValueType.Equals(iceberg.VariantType{}))
+ assert.True(t, mapType.ValueType().Equals(iceberg.VariantType{}))
}
func TestVariantInStructField(t *testing.T) {
diff --git a/types_verification_test.go b/types_verification_test.go
index 8797d38aa..5c23b6dc3 100644
--- a/types_verification_test.go
+++ b/types_verification_test.go
@@ -166,13 +166,13 @@ func decodedTypeOf(typ iceberg.Type) map[string]any {
return map[string]any{"type": "struct", "fields": fields}
case *iceberg.ListType:
return map[string]any{
- "type": "list", "element-id": typ.ElementID,
- "element-required": typ.ElementRequired, "element":
decodedTypeOf(typ.Element),
+ "type": "list", "element-id": typ.ElementID(),
+ "element-required": typ.ElementRequired(), "element":
decodedTypeOf(typ.Element()),
}
case *iceberg.MapType:
return map[string]any{
- "type": "map", "key-id": typ.KeyID, "key":
decodedTypeOf(typ.KeyType),
- "value-id": typ.ValueID, "value-required":
typ.ValueRequired, "value": decodedTypeOf(typ.ValueType),
+ "type": "map", "key-id": typ.KeyID(), "key":
decodedTypeOf(typ.KeyType()),
+ "value-id": typ.ValueID(), "value-required":
typ.ValueRequired(), "value": decodedTypeOf(typ.ValueType()),
}
default:
return map[string]any{"type": typ.Type()}
diff --git a/variant_extract_test.go b/variant_extract_test.go
index 5901aaede..0e013bd41 100644
--- a/variant_extract_test.go
+++ b/variant_extract_test.go
@@ -203,7 +203,7 @@ func TestColumnPathSegments(t *testing.T) {
assert.Equal(t, []string{"a.b"}, topLevel.columnPathSegments(2))
nested := NewSchema(0, NestedField{ID: 2, Name: "wrap.per", Type:
&StructType{
- FieldList: []NestedField{{ID: 3, Name: "pay.load", Type:
VariantType{}}},
+ fields: []NestedField{{ID: 3, Name: "pay.load", Type:
VariantType{}}},
}})
assert.Equal(t, []string{"wrap.per", "pay.load"},
nested.columnPathSegments(3))
}
diff --git a/view/metadata.go b/view/metadata.go
index f1423d9cc..7630bdf59 100644
--- a/view/metadata.go
+++ b/view/metadata.go
@@ -439,7 +439,7 @@ func cloneSchema(schema *iceberg.Schema) *iceberg.Schema {
return iceberg.NewSchemaWithIdentifiers(
schema.ID,
- slices.Clone(schema.IdentifierFieldIDs),
+ schema.IdentifierFieldIDs(),
schema.Fields()...,
)
}
diff --git a/view/metadata_builder.go b/view/metadata_builder.go
index 411f616f0..2e3b2d172 100644
--- a/view/metadata_builder.go
+++ b/view/metadata_builder.go
@@ -241,7 +241,7 @@ func (b *MetadataBuilder) addSchema(schema *iceberg.Schema)
(int, error) {
newSchema := schema
// Build a fresh schema if we reset the ID
if schema.ID != newSchemaID {
- newSchema = iceberg.NewSchemaWithIdentifiers(newSchemaID,
schema.IdentifierFieldIDs, schema.Fields()...)
+ newSchema = iceberg.NewSchemaWithIdentifiers(newSchemaID,
schema.IdentifierFieldIDs(), schema.Fields()...)
}
b.schemaList = append(b.schemaList, newSchema)
diff --git a/view/metadata_test.go b/view/metadata_test.go
index abe133a00..a15580a91 100644
--- a/view/metadata_test.go
+++ b/view/metadata_test.go
@@ -990,7 +990,6 @@ func TestMetadataGettersReturnDefensiveCopies(t *testing.T)
{
currentSchema := md.CurrentSchema()
currentSchema.ID = 99
- currentSchema.IdentifierFieldIDs[0] = 99
schemas := md.Schemas()
schemas[0].ID = 98
@@ -1010,7 +1009,6 @@ func TestMetadataGettersReturnDefensiveCopies(t
*testing.T) {
assert.Equal(t, "select * from ns.tbl",
md.CurrentVersion().Representations[0].SQL)
assert.Equal(t, "accounting", md.CurrentVersion().DefaultNamespace[0])
assert.Equal(t, 0, md.CurrentSchema().ID)
- assert.Equal(t, 1, md.CurrentSchema().IdentifierFieldIDs[0])
assert.Equal(t, 0, md.Schemas()[0].ID)
assert.Equal(t, 0, md.SchemasByID()[0].ID)
assert.Equal(t, int64(1), md.VersionLog()[0].VersionID)
@@ -1038,22 +1036,23 @@ func TestCloneSchemaCopiesNestedValues(t *testing.T) {
)
cloned := cloneSchema(schema)
- cloned.IdentifierFieldIDs[0] = 99
- fields := cloned.FieldsRef(iceinternal.SchemaRef{})
- structField := fields[0].Type.(*iceberg.StructType)
- structField.FieldList[0].Name = "changed"
- listField := fields[1].Type.(*iceberg.ListType)
- listField.Element.(*iceberg.StructType).FieldList[0].Name = "changed"
- mapField := fields[2].Type.(*iceberg.MapType)
- mapField.ValueType.(*iceberg.StructType).FieldList[0].Name = "changed"
-
- assert.Equal(t, []int{1}, schema.IdentifierFieldIDs)
+ cloned.FieldsRef(iceinternal.SchemaRef{})[0].Name = "changed"
+
+ // Nested types can't be written from this package, so check that the
+ // clone holds its own nested type values instead.
+ srcFields := schema.FieldsRef(iceinternal.SchemaRef{})
+ clonedFields := cloned.FieldsRef(iceinternal.SchemaRef{})
+ assert.NotSame(t, srcFields[0].Type, clonedFields[0].Type)
+ assert.NotSame(t, srcFields[1].Type.(*iceberg.ListType).Element(),
clonedFields[1].Type.(*iceberg.ListType).Element())
+ assert.NotSame(t, srcFields[2].Type.(*iceberg.MapType).ValueType(),
clonedFields[2].Type.(*iceberg.MapType).ValueType())
+
+ assert.Equal(t, "struct", schema.Field(0).Name)
originalStruct := schema.Field(0).Type.(*iceberg.StructType)
assert.Equal(t, "nested", originalStruct.Field(0).Name)
assert.Equal(t, "01", originalStruct.Field(0).InitialDefault)
assert.Equal(t, "02", originalStruct.Field(0).WriteDefault)
- assert.Equal(t, "element",
schema.Field(1).Type.(*iceberg.ListType).Element.(*iceberg.StructType).Field(0).Name)
- assert.Equal(t, "value",
schema.Field(2).Type.(*iceberg.MapType).ValueType.(*iceberg.StructType).Field(0).Name)
+ assert.Equal(t, "element",
schema.Field(1).Type.(*iceberg.ListType).Element().(*iceberg.StructType).Field(0).Name)
+ assert.Equal(t, "value",
schema.Field(2).Type.(*iceberg.MapType).ValueType().(*iceberg.StructType).Field(0).Name)
}
var exampleViewJSON = `{
diff --git a/website/src/api.md b/website/src/api.md
index cbc05533d..a579e065b 100644
--- a/website/src/api.md
+++ b/website/src/api.md
@@ -153,7 +153,7 @@ schema := iceberg.NewSchema(1,
)
```
-For nested types use `&iceberg.StructType{...}`, `&iceberg.ListType{...}`, or
`&iceberg.MapType{...}`. Use `NewSchemaWithIdentifiers(id, identifierIDs,
fields...)` to mark identifier columns.
+For nested types use `iceberg.NewStructType(fields...)`,
`iceberg.NewListType(elementID, element, required)`, or
`iceberg.NewMapType(keyID, key, valueID, value, valueRequired)`. Their fields
can't be assigned directly: read them through accessors, and to change one,
build a new value. Use `NewSchemaWithIdentifiers(id, identifierIDs, fields...)`
to mark identifier columns.
#### Create
diff --git a/website/src/releases.md b/website/src/releases.md
index 5591a2978..2fd3d6ed8 100644
--- a/website/src/releases.md
+++ b/website/src/releases.md
@@ -68,7 +68,14 @@ Per-release notes (highlights, breaking changes,
contributors) are published on
- **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)).
+- **`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 struct's field list is no longer
exported; see the next note.
+- **Nested type fields are unexported.** `StructType`, `ListType` and
`MapType` can no longer be built with keyed struct literals, and their fields
can no longer be assigned (see
[#2062](https://github.com/apache/iceberg-go/issues/2062)). Build them with
`NewStructType`, `NewListType` and `NewMapType`, and to change one, build a new
value. Read them through methods named after the old fields:
+ - `StructType.FieldList` becomes `Fields()` (a copy), or `NumFields()` and
`Field(i)` to read without copying.
+ - `ListType.ElementID`, `Element` and `ElementRequired` become
`ElementID()`, `Element()` and `ElementRequired()`.
+ - `MapType.KeyID`, `KeyType`, `ValueID`, `ValueType` and `ValueRequired`
become `KeyID()`, `KeyType()`, `ValueID()`, `ValueType()` and `ValueRequired()`.
+ - `Schema.IdentifierFieldIDs` is unexported too and becomes
`IdentifierFieldIDs()`, which returns a copy. Set the IDs with
`NewSchemaWithIdentifiers`, which keeps its own copy of the slice it is given.
+
+ Pointers to these types and `Schema` encode to the same JSON as before.
Values of these types, such as the result of `Schema.AsStruct()`, now encode
like pointers instead of a partial form without `"type"`.
- **`io.StatIO.Stat` accepts a context.** The method now takes a
`context.Context` before the path, so custom `StatIO` implementations and
callers must pass the operation context.
- **Commits retry conflicts by default.** `commit.retry.num-retries` now
defaults to `4`, as in Java and PyIceberg, so `Commit` refreshes and replays a
conflicting commit up to four times before returning `ErrCommitFailed`. Set it
to `0` to keep failing on the first conflict. `table.CommitNumRetriesDefault`
changes from `0` to `4`.
- **The first `Delete` on a v3 table upgraded from v2 can fail with
`ErrCommitFailed`.** A merge-on-read `Delete` that gives a data file its first
deletion vector now folds that file's v2 position deletes into the vector, so
those deletes no longer reappear after the upgrade, and drops the file-scoped
v2 position delete files in the same commit. Like any commit that removes
delete files, it is not replayed: if another writer commits first, it returns
`ErrCommitFailed` instead of refreshi [...]