Repository navigation
feat: adding schema update methods - #431
Shreyas220 wants to merge 21 commits into
Conversation
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>
bf2712e to
ebcbce9
Compare
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>
|
Hey @laskoviymishka @zeroshade @xixipi-lining I think we can start reviewing this PR now I'll keep adding tests in the background |
Signed-off-by: Shreyas220 <[email protected]>
| "github.com/apache/iceberg-go" | ||
| ) | ||
|
|
||
| type UpdateSchema struct { |
There was a problem hiding this comment.
There needs to be a transaction being managed here since updating the schema needs to tracked as part of a transaction
Signed-off-by: Shreyas220 <[email protected]>
584d1da to
8093bd3
Compare
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]>
8093bd3 to
9a7c04a
Compare
|
I'll go through this again today and give a review. |
zeroshade
left a comment
There was a problem hiding this comment.
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.
| 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 | ||
| } |
There was a problem hiding this comment.
can we use iceberge.PromoteType ?
There was a problem hiding this comment.
@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?
There was a problem hiding this comment.
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
| 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) { |
There was a problem hiding this comment.
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
| type ColumnUpdate struct { | ||
| Type iceberg.Type // nil means no change | ||
| Doc *string // nil means no change | ||
| Default *any // nil means no change |
There was a problem hiding this comment.
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
| o := oldType.(iceberg.DecimalType) | ||
| n, ok := newType.(iceberg.DecimalType) | ||
| return ok && o.Scale() == n.Scale() && n.Precision() > o.Precision() | ||
| case "date": |
There was a problem hiding this comment.
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)?
There was a problem hiding this comment.
Agreed. Let's leave this out for now and handle it separately
|
@Shreyas220 Hi, just wondering if there's any plan to continue with this PR? |
Hey @xixipi-lining , yes, sorry for the delay! |
Signed-off-by: Shreyas220 <[email protected]> chore: reviews and adding integration test Signed-off-by: Shreyas220 <[email protected]>
5571e18 to
fe9d0c0
Compare
Signed-off-by: Shreyas220 <[email protected]>
Signed-off-by: Shreyas220 <[email protected]>
| io.S3Region: "us-east-1", | ||
| io.S3AccessKeyID: "admin", | ||
| io.S3SecretAccessKey: "password", | ||
| io.S3EndpointURL: "http://localhost:9000", |
There was a problem hiding this comment.
do we need this instead relying on the corresponding AWS_ENDPOINT env var?
| updates map[int]*iceberg.NestedField | ||
| adds map[int][]*iceberg.NestedField |
There was a problem hiding this comment.
do these need to map to pointers instead of just mapping to values?
| // | ||
| // 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) { |
There was a problem hiding this comment.
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.
Signed-off-by: Shreyas220 <[email protected]>
|
Again, apologies for the delay 🙇 !! @zeroshade 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
and then use the same old logic to rebuild the schema and commit using |
| } | ||
|
|
||
| switch pf.Type.(type) { | ||
| case *iceberg.StructType, *iceberg.MapType, *iceberg.ListType: |
There was a problem hiding this comment.
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.
| } | ||
| } | ||
|
|
||
| newID := builder.assignNewColumnID() |
There was a problem hiding this comment.
If the added field is a MapType, keyID and valueID also need to be assigned.
| } | ||
|
|
||
| // RemoveLastOperation removes the most recently added operation | ||
| func (us *UpdateSchema) RemoveLastOperation() *UpdateSchema { |
There was a problem hiding this comment.
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?
There was a problem hiding this comment.
I agree here, I don't think there's any good use for the Reset or RemoveLastOperation methods.
| case int64, int: | ||
| return NewLiteral(int64(reflect.ValueOf(x).Int())), nil |
There was a problem hiding this comment.
make these two separate cases, reflect is costly and expensive
| // 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") |
| type SchemaOperation interface { | ||
| Apply(builder *schemaBuilder) error | ||
| Validate(schema *iceberg.Schema, settings *validationSettings) error | ||
| String() string | ||
| } |
There was a problem hiding this comment.
since these operate only on internal types, why are we bothering to export this type?
| op moveOp | ||
| } | ||
|
|
||
| func NewUpdateSchema(txn *Transaction, s *iceberg.Schema, lastColumnID int) *UpdateSchema { |
| } | ||
|
|
||
| // RemoveLastOperation removes the most recently added operation | ||
| func (us *UpdateSchema) RemoveLastOperation() *UpdateSchema { |
There was a problem hiding this comment.
I agree here, I don't think there's any good use for the Reset or RemoveLastOperation methods.
| settings := &validationSettings{ | ||
| allowIncompatibleChanges: us.allowIncompatibleChanges, | ||
| caseSensitive: us.caseSensitive, | ||
| } |
There was a problem hiding this comment.
why use a pointer for this? just take validationSettings instead of a *validationSettings
| // No operations means no changes | ||
| if len(us.operations) == 0 { | ||
| return us.schema, nil | ||
| } |
There was a problem hiding this comment.
should we do this before calling validate?
| 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), | ||
| ) |
There was a problem hiding this comment.
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.
| if len(us.errors) > 0 { | ||
| return fmt.Errorf("validation failed with %d errors: %v", len(us.errors), us.errors) | ||
| } | ||
| return nil |
There was a problem hiding this comment.
return errors.Join(us.errors) much more concise and simple 😄
| // Only update name mapping if we have adds/updates that might need it | ||
| hasAdds := false | ||
| hasUpdates := false |
There was a problem hiding this comment.
we're not doing different behaviors based on hasAdds vs hasUpdates so just use one variable
|
@Shreyas220 Hi, I was wondering if you are still working on this PR ? |
|
Hey @batyrchary , |
|
@Shreyas220 I've created a new PR to implement the UpdateSchema functionality. Please help me review it. #596 |
### 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) ```
Supported Operations
All operations are batched and applied atomically via Apply() which returns a new
SchemaIt is called from the transaction
1 AddColumn(...)
2 UpdateColumn(...)
Supported Updates:
3 DeleteColumn(...)
4 Move(column, anotherColumn, op)
Allowed operation
Type promotion allowed