Skip to content

feat: adding schema update methods - #431

Closed
Shreyas220 wants to merge 21 commits into
apache:mainfrom
Shreyas220:schema-evolution
Closed

Shreyas220 wants to merge 21 commits into
apache:mainfrom
Shreyas220:schema-evolution

Conversation

@Shreyas220

@Shreyas220 Shreyas220 commented May 14, 2025 •

Copy link
Copy Markdown
Contributor

Supported Operations

All operations are batched and applied atomically via Apply() which returns a new Schema

It is called from the transaction

schemaUpdater := txn.UpdateSchema()

// Add new column
schemaUpdater.AddColumn([]string{"phone"}, false, iceberg.StringType{}, "", nil)

err := schemaUpdater.Commit() //generate update and requirement and does txn.apply

1 AddColumn(...)

  • Validates the parent path and checks if the new column is already present.
  • Enforces default values for required columns (unless AllowIncompatibleChanges)
  • Type validation for initial default values

2 UpdateColumn(...)

Supported Updates:

  • Type Promotion: Only spec-compliant widening (mentioned below)
  • Documentation: Arbitrary text updates
  • Default Values: Re-validated against column type
  • Nullability: Optional↔Required with compatibility checks

3 DeleteColumn(...)

  • Rejects deletion if the target also appears in adds or updates (prevents contradictory intents).

4 Move(column, anotherColumn, op)

  • Both columns must share the same parent

Allowed operation

  • OpFirst: Move to the beginning
  • OpBefore: Position before reference column
  • OpAfter: Position after reference column

Type promotion allowed

  • int32 → int64
  • float32 → float64
  • decimal(P1,S) → decimal(P2,S) where P2 > P1
  • date → timestamp/timestamp_ns (spec V3 allows it now)

Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Signed-off-by: Shreyas220 <[email protected]>
Comment thread table/update_schema.go Resolved
@Shreyas220
Shreyas220 marked this pull request as ready for review June 5, 2025 20:17
@Shreyas220

Shreyas220 commented Jun 5, 2025 •

Copy link
Copy Markdown
Contributor Author

Hey @laskoviymishka @zeroshade @xixipi-lining

I think we can start reviewing this PR now

I'll keep adding tests in the background
also let me know if i am missing some important update operations here

@Shreyas220 Shreyas220 changed the title [WIP] feat: adding schema update methods feat: adding schema update methods Jun 6, 2025
Signed-off-by: Shreyas220 <[email protected]>
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved

@laskoviymishka laskoviymishka left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Don't panic

Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema_test.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go
"github.com/apache/iceberg-go"
)

type UpdateSchema struct {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There needs to be a transaction being managed here since updating the schema needs to tracked as part of a transaction

Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
Comment thread table/update_schema.go Resolved
@Shreyas220
Shreyas220 requested a review from nandorKollar June 11, 2025 18:42
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>

feat: adding commit method

Signed-off-by: Shreyas220 <[email protected]>

feat: adding commit method

Signed-off-by: Shreyas220 <[email protected]>
@zeroshade

Copy link
Copy Markdown
Member

I'll go through this again today and give a review.

@zeroshade zeroshade left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Looking really good so far, can we add tests to table_test.go that actually write the updated table with the new schema and then read it back to ensure everything worked? Possibly even testing against the REST catalog?

We should also validate that when performing a read/scan against the table with the updated schema that it is successful and either fills in nulls for the new columns or the default value.

Comment thread table/update_schema.go Outdated
Comment on lines +379 to +398
func allowedPromotion(oldType, newType iceberg.Type) bool {
switch old := oldType.(type) {

case iceberg.PrimitiveType:
switch old.Type() {
case "int":
return newType.Type() == "long"
case "float":
return newType.Type() == "double"
case "decimal":
o := oldType.(iceberg.DecimalType)
n, ok := newType.(iceberg.DecimalType)
return ok && o.Scale() == n.Scale() && n.Precision() > o.Precision()
case "date":
return newType.Type() == "timestamp" || newType.Type() == "timestamp_ns"
}
}

return false
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

can we use iceberge.PromoteType ?

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@zeroshade looking at iceberg.PromoteType I noticed that date to timestamp promotion isn't implemented there? I think that's allowed as per V3 spec, isn't it?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

iceberg-go hasn't done any updating for v3 yet. Since it's allowed in v3, but not in v2 we'd likely have to conditionally allow the promotion

Comment thread table/update_schema.go Outdated
return fmt.Errorf("default literal of type %s is not assignable to of type %s", litType.String(), prim.Type())
}

func literalFromAny(v any) (iceberg.Literal, error) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Would it make sense to make this a function in literals.go where a user with an any can call this and get (Literal, error) but if they know the type, they can use NewLiteral and not have to worry about handling an error

Comment thread table/update_schema.go Outdated
type ColumnUpdate struct {
Type iceberg.Type // nil means no change
Doc *string // nil means no change
Default *any // nil means no change

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

just use any not *any. if the any is nil then there's no change. We don't want to be using *any at all.

Alternately, we could use iceberg.Optional[...] for some of theses? Dunno if it's worthwhile

Comment thread table/update_schema.go Outdated
o := oldType.(iceberg.DecimalType)
n, ok := newType.(iceberg.DecimalType)
return ok && o.Scale() == n.Scale() && n.Precision() > o.Precision()
case "date":

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

After reading the spec, I think there's possibly one extra detail to check: verify that the date field which is about to be promoted is not referenced in partitions. From the spec:

Type promotion is not allowed for a field that is referenced by source-id or source-ids of a partition field if the partition transform would produce a different value after promoting the type. For example, bucket[N] produces different hash values for 34 and "34" (2017239379 != -427558391) but the same value for 34 and 34L; when an int field is the source for a bucket partition field, it may be promoted to long but not to string. This may happen for the following type promotion cases:

date to timestamp or timestamp_ns

@zeroshade what do you think, maybe it is better to leave this out for now, and handle this promotion separately (this was added in V3, so rest of promotion confirm to V2 spec)?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Agreed. Let's leave this out for now and handle it separately

@xixipi-lining

Copy link
Copy Markdown
Contributor

@Shreyas220 Hi, just wondering if there's any plan to continue with this PR?

@Shreyas220

Shreyas220 commented Jul 5, 2025 •

Copy link
Copy Markdown
Contributor Author

@Shreyas220 Hi, just wondering if there's any plan to continue with this PR?

Hey @xixipi-lining , yes, sorry for the delay!
I had addressed most of the feedback earlier, but realised I forgot to push the latest changes (got a bit busy with work) 😓 .
I'll add an integration test and push the updates.
Thanks for the reminder !

Signed-off-by: Shreyas220 <[email protected]>

chore: reviews and adding integration test

Signed-off-by: Shreyas220 <[email protected]>
@Shreyas220
Shreyas220 requested a review from zeroshade July 5, 2025 14:48
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>

@zeroshade zeroshade left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Few more nit picks

Comment thread catalog/rest/rest_integration_test.go Outdated
io.S3Region: "us-east-1",
io.S3AccessKeyID: "admin",
io.S3SecretAccessKey: "password",
io.S3EndpointURL: "http://localhost:9000",

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do we need this instead relying on the corresponding AWS_ENDPOINT env var?

Comment thread table/update_schema.go Outdated
Comment on lines +35 to +36
updates map[int]*iceberg.NestedField
adds map[int][]*iceberg.NestedField

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

do these need to map to pointers instead of just mapping to values?

Comment thread table/update_schema.go Outdated
//
// us.AddColumn([]string{"a","b"}, true, iceberg.StringType{}, "doc", "default")
// us.AddColumn([]string{"a","b"}, true, iceberg.StringType{}, "doc", "default")
func (us *UpdateSchema) AddColumn(path []string, required bool, dataType iceberg.Type, doc string, initialDefault any) (*UpdateSchema, error) {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

We should either return just error or we should return just *UpdateSchema and defer all the actual operations to a Build() method.

There's no reason to return both because you don't need the returned *UpdateSchema to continue, so we are preventing chaining while not providing anything in return. So we should embrace the Builder pattern entirely, or we should just have the single error return.

@Shreyas220

Shreyas220 commented Jul 28, 2025 •

Copy link
Copy Markdown
Contributor Author

Again, apologies for the delay 🙇 !!

@zeroshade
even i prefer returning *updateSchema and ability to chain the update operations
deferred schema update operations in build

Summary of change is that the logic present in each (add, update,e, delete move ) operation before is now divided into 2 parts, that are validations and apply

  • validation will go through all the operations, collect all the errors and return
  • apply will rebuild the old schema update, add, update and move... etc structs

and then use the same old logic to rebuild the schema and commit

using operations []SchemaOperation to try to preserve the order of operation

Comment thread table/update_schema.go
}

switch pf.Type.(type) {
case *iceberg.StructType, *iceberg.MapType, *iceberg.ListType:

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the parent field found in that way is a MapType, we need to check whether its value type is a structure. Likewise, for ListType, we need to check if the element type is a structure.

Comment thread table/update_schema.go
}
}

newID := builder.assignNewColumnID()

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

If the added field is a MapType, keyID and valueID also need to be assigned.

Comment thread table/update_schema.go
}

// RemoveLastOperation removes the most recently added operation
func (us *UpdateSchema) RemoveLastOperation() *UpdateSchema {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I'm a little confused — when exactly do we need to use the Reset and RemoveLastOperation methods? Exposing the internal op queues doesn't seem to offer much benefit. Maybe a simpler interface would be sufficient?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree here, I don't think there's any good use for the Reset or RemoveLastOperation methods.

Comment thread literals.go
Comment on lines +215 to +216
case int64, int:
return NewLiteral(int64(reflect.ValueOf(x).Int())), nil

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

make these two separate cases, reflect is costly and expensive

Comment thread table/table_test.go
// validate that no error is logged
logOutput := logBuf.String()
t.NotContains(logOutput, "Warning: Failed to delete old metadata file")
t.NotContains(logOutput, "no such file or directory")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why are we removing this?

Comment thread table/update_schema.go
Comment on lines +27 to +31
type SchemaOperation interface {
Apply(builder *schemaBuilder) error
Validate(schema *iceberg.Schema, settings *validationSettings) error
String() string
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

since these operate only on internal types, why are we bothering to export this type?

Comment thread table/update_schema.go
op moveOp
}

func NewUpdateSchema(txn *Transaction, s *iceberg.Schema, lastColumnID int) *UpdateSchema {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

needs a docstring comment

Comment thread table/update_schema.go
}

// RemoveLastOperation removes the most recently added operation
func (us *UpdateSchema) RemoveLastOperation() *UpdateSchema {

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I agree here, I don't think there's any good use for the Reset or RemoveLastOperation methods.

Comment thread table/update_schema.go
Comment on lines +200 to +203
settings := &validationSettings{
allowIncompatibleChanges: us.allowIncompatibleChanges,
caseSensitive: us.caseSensitive,
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

why use a pointer for this? just take validationSettings instead of a *validationSettings

Comment thread table/update_schema.go
Comment on lines +224 to +227
// No operations means no changes
if len(us.operations) == 0 {
return us.schema, nil
}

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

should we do this before calling validate?

Comment thread table/update_schema.go
Comment on lines +289 to +312
if existingSchemaID == nil {
// Get the final lastColumnID from the builder
builder := &schemaBuilder{
deletes: make(map[int]struct{}),
updates: make(map[int]*iceberg.NestedField),
adds: make(map[int][]*iceberg.NestedField),
moves: make(map[int][]moveReq),
lastColumnID: us.lastColumnID,
baseSchema: us.schema,
settings: &validationSettings{
allowIncompatibleChanges: us.allowIncompatibleChanges,
caseSensitive: us.caseSensitive,
},
}

for _, op := range us.operations {
if err := op.Apply(builder); err != nil {
return nil, nil, fmt.Errorf("failed to recompute lastColumnID: %w", err)
}
}
updates = append(updates,
NewAddSchemaUpdate(newSchema, builder.lastColumnID, false),
NewSetCurrentSchemaUpdate(newSchema.ID),
)

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This seems like a waste to have to rebuild the schema again. Can we somehow store/update the lastColumnID after calling Build() rather than redo the build here.

Comment thread table/update_schema.go
Comment on lines +211 to +214
if len(us.errors) > 0 {
return fmt.Errorf("validation failed with %d errors: %v", len(us.errors), us.errors)
}
return nil

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

return errors.Join(us.errors) much more concise and simple 😄

Comment thread table/update_schema.go
Comment on lines +806 to +808
// Only update name mapping if we have adds/updates that might need it
hasAdds := false
hasUpdates := false

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we're not doing different behaviors based on hasAdds vs hasUpdates so just use one variable

@batyrchary

Copy link
Copy Markdown

@Shreyas220 Hi, I was wondering if you are still working on this PR ?

@Shreyas220

Copy link
Copy Markdown
Contributor Author

Hey @batyrchary ,
I haven’t been able to find time to work on this lately. If you’d like to pick it up, please go ahead
I’m happy to help with reviews. 🙂

@xixipi-lining

Copy link
Copy Markdown
Contributor

@Shreyas220 I've created a new PR to implement the UpdateSchema functionality. Please help me review it. #596

zeroshade pushed a commit that referenced this pull request Oct 23, 2025
### Summary

This PR introduces initial schema evolution capabilities, allowing users
to modify table schemas through a fluent API. This work was originally
started by @Shreyas220 in PR #431 , but due to time constraints, I'm
continuing the implementation.

### Key Features

- **Add Columns**: Support for adding primitive types, structs, lists,
and maps
- **Delete Columns**: Remove fields from the schema
- **Update Columns**: Modify field properties including name, type,
nullability, and documentation
- **Move Columns**: Reorder fields with operations like `MoveFirst`,
`MoveBefore`, and `MoveAfter`
- **Rename Columns**: Change field names
- **Basic Validation**: Type checking and compatibility validation

### API Usage

```go
// Create a transaction and update schema
txn := table.NewTransaction()
updateSchema := txn.UpdateSchema(true, false) // caseSensitive=true, allowIncompatibleChanges=false

// Add a new column
updateSchema.AddColumn([]string{"gender"}, iceberg.PrimitiveTypes.String, "User gender", false, nil)

// Add nested column in struct
updateSchema.AddColumn([]string{"address", "country"}, iceberg.PrimitiveTypes.String, "Country code", false, iceberg.StringLiteral("US"))

// Add complex nested structure
updateSchema.AddColumn([]string{"profile"}, &iceberg.StructType{
    FieldList: []iceberg.NestedField{
        {Name: "bio", Type: iceberg.PrimitiveTypes.String, Required: false},
        {Name: "avatar", Type: iceberg.PrimitiveTypes.String, Required: false},
    },
}, "User profile", false, nil)

// Add list type
updateSchema.AddColumn([]string{"tags"}, &iceberg.ListType{
    Element: iceberg.PrimitiveTypes.String,
    ElementRequired: false,
}, "User tags", false, nil)

// Rename a column
updateSchema.RenameColumn([]string{"age"}, "user_age")

// Update column properties
updateSchema.UpdateColumn([]string{"name"}, ColumnUpdate{
    Required: iceberg.Optional[bool]{Valid: true, Val: true},
    Doc: iceberg.Optional[string]{Valid: true, Val: "User's full name"},
})

// Move column to first position
updateSchema.MoveFirst([]string{"id"})

// Move column before another column
updateSchema.MoveBefore([]string{"name"}, []string{"age"})

// Delete a column
updateSchema.DeleteColumn([]string{"old_field"})

// Chain multiple operations
updateSchema.
    AddColumn([]string{"email"}, iceberg.PrimitiveTypes.String, "Email address", true, nil).
    RenameColumn([]string{"phone"}, "phone_number").
    MoveAfter([]string{"email"}, []string{"name"}).
    DeleteColumn([]string{"deprecated_field"})

// Preview changes without committing
newSchema, err := updateSchema.Apply()
if err != nil {
    // Handle validation errors
    return err
}

// Commit the changes
err := updateSchema.Commit()
if err != nil {
    return err
}

// Commit the entire transaction
updatedTable, err := txn.Commit(ctx)
```
@Shreyas220 Shreyas220 closed this Oct 30, 2025
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

6 participants