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

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


The following commit(s) were added to refs/heads/main by this push:
     new 2a7f865  Reuse existing schema IDs if proper (#144)
2a7f865 is described below

commit 2a7f8651f2cf5ea2e0ff214a6e94ab3101e354a8
Author: Alex Stephen <[email protected]>
AuthorDate: Thu Nov 19 14:37:05 2026 -0800

    Reuse existing schema IDs if proper (#144)
    
    * Reuse existing schema when possible
    
    * want to make this easier to understand
    
    * Use strings.Builder in updateActions test helper
    
    Fixes perfsprint concat-loop lint failure.
    
    * comments
    
    addressed comment
    
    * Test reverting past a dropped field reuses the existing schema
    
    * Expect exact revert past a dropped field to reuse schema 0
---
 internal/provider/resource_table.go      | 172 +++++++------
 internal/provider/resource_table_test.go | 428 ++++++++++++++++++++++++++++++-
 2 files changed, 520 insertions(+), 80 deletions(-)

diff --git a/internal/provider/resource_table.go 
b/internal/provider/resource_table.go
index b88121c..89ec8a9 100644
--- a/internal/provider/resource_table.go
+++ b/internal/provider/resource_table.go
@@ -443,6 +443,14 @@ func (r *icebergTableResource) 
calculatePropertyUpdates(ctx context.Context, pla
        return updates
 }
 
+// calculateSchemaUpdates, calculatePartitionUpdates and 
calculateSortOrderUpdates
+// each make the planned schema, spec or sort order current in three steps:
+//
+//  1. It is already current: no updates.
+//  2. It matches one already in the table's metadata: set that existing ID as
+//     current. The catalog dedupes on add (it would keep the old ID and add
+//     nothing), so adding it again and pointing at a new or last-added ID 
fails.
+//  3. It is new: add it and set it as current.
 func (r *icebergTableResource) calculateSchemaUpdates(ctx context.Context, 
plan, state *icebergTableResourceModel, tbl *table.Table, diags 
*diag.Diagnostics) []table.Update {
        var planSchema, stateSchema icebergTableSchema
        d := plan.Schema.As(ctx, &planSchema, basetypes.ObjectAsOptions{})
@@ -487,133 +495,143 @@ func (r *icebergTableResource) 
calculateSchemaUpdates(ctx context.Context, plan,
                return nil
        }
 
+       if tbl.Schema().Equals(planIceberg) {
+               return nil
+       }
+
        // Reject changes that aren't a valid Iceberg evolution before 
committing.
+       // This includes reverting to an earlier schema: that is still an 
evolution
+       // from the current schema, and may undo a promotion that data relies 
on.
        if err := validateSchemaEvolution(tbl.Schema(), planIceberg); err != 
nil {
                diags.AddError("invalid schema evolution", err.Error())
 
                return nil
        }
-       if err := validateNewFieldIDs(tbl.Metadata(), planIceberg); err != nil {
-               diags.AddError("invalid field id", err.Error())
 
-               return nil
-       }
-
-       // Find the highest existing schema ID to ensure the new one is unique.
-       maxSchemaID := int64(0)
-       for _, s := range tbl.Metadata().Schemas() {
-               if int64(s.ID) > maxSchemaID {
-                       maxSchemaID = int64(s.ID)
+       // Returning to an earlier schema: point back at its existing ID.
+       maxSchemaID := 0
+       for _, existing := range tbl.Metadata().Schemas() {
+               if existing.Equals(planIceberg) {
+                       return 
[]table.Update{table.NewSetCurrentSchemaUpdate(existing.ID)}
                }
+               maxSchemaID = max(maxSchemaID, existing.ID)
        }
 
-       newSchemaID := maxSchemaID + 1
-       planSchema.ID = types.Int64Value(newSchemaID)
-       planIceberg, err = planSchema.ToIceberg()
-       if err != nil {
-               diags.AddError("failed to convert plan schema with new ID", 
err.Error())
+       // Only a genuinely new schema can introduce field IDs, so an exact 
revert
+       // that re-declares a dropped column under its old ID is not rejected.
+       if err := validateNewFieldIDs(tbl.Metadata(), planIceberg); err != nil {
+               diags.AddError("invalid field id", err.Error())
 
                return nil
        }
 
-       // Return two events:
-       // 1. Add the schema with new schema ID.
-       // 2. Set the table schema explicitly to that new ID.
+       // A new schema: add it under the next unused ID and make it current.
+       planIceberg.ID = maxSchemaID + 1
+
        return []table.Update{
                table.NewAddSchemaUpdate(planIceberg),
-               table.NewSetCurrentSchemaUpdate(int(newSchemaID)),
+               table.NewSetCurrentSchemaUpdate(planIceberg.ID),
        }
 }
 
 func (r *icebergTableResource) calculatePartitionUpdates(ctx context.Context, 
plan *icebergTableResourceModel, tbl *table.Table, diags *diag.Diagnostics) 
[]table.Update {
-       spec := tbl.Spec()
-       if plan.PartitionSpec.IsUnknown() {
-               if spec.NumFields() > 0 {
-                       // Create a new unpartitioned spec and set it as default
-                       unpartitionedSpec := iceberg.NewPartitionSpec()
-
-                       return []table.Update{
-                               
table.NewAddPartitionSpecUpdate(&unpartitionedSpec, false),
-                               table.NewSetDefaultSpecUpdate(-1),
-                       }
-               }
-
-               return nil
-       }
-
        if plan.PartitionSpec.IsNull() {
                return nil
        }
 
-       var planSpec icebergTablePartitionSpec
-       d := plan.PartitionSpec.As(ctx, &planSpec, basetypes.ObjectAsOptions{})
-       diags.Append(d...)
+       newIcebergSpec := iceberg.NewPartitionSpec()
+       if !plan.PartitionSpec.IsUnknown() {
+               var planSpec icebergTablePartitionSpec
+               d := plan.PartitionSpec.As(ctx, &planSpec, 
basetypes.ObjectAsOptions{})
+               diags.Append(d...)
 
-       if diags.HasError() {
-               return nil
-       }
+               if diags.HasError() {
+                       return nil
+               }
 
-       newIcebergSpec, err := planSpec.ToIceberg()
-       if err != nil {
-               diags.AddError("failed to convert partition spec", err.Error())
+               spec, err := planSpec.ToIceberg()
+               if err != nil {
+                       diags.AddError("failed to convert partition spec", 
err.Error())
 
+                       return nil
+               }
+               newIcebergSpec = *spec
+       }
+
+       current := tbl.Spec()
+       if current.CompatibleWith(&newIcebergSpec) {
                return nil
        }
 
-       // Compare with current spec
-       if !spec.CompatibleWith(newIcebergSpec) {
-               return []table.Update{
-                       table.NewAddPartitionSpecUpdate(newIcebergSpec, false),
-                       table.NewSetDefaultSpecUpdate(-1),
+       // Returning to an earlier spec: point back at its existing ID.
+       for _, existing := range tbl.Metadata().PartitionSpecs() {
+               if existing.CompatibleWith(&newIcebergSpec) {
+                       return 
[]table.Update{table.NewSetDefaultSpecUpdate(existing.ID())}
                }
        }
 
-       return nil
+       // A new spec: add it and make it the default.
+       return []table.Update{
+               table.NewAddPartitionSpecUpdate(&newIcebergSpec, false),
+               table.NewSetDefaultSpecUpdate(-1),
+       }
 }
 
 func (r *icebergTableResource) calculateSortOrderUpdates(ctx context.Context, 
plan *icebergTableResourceModel, tbl *table.Table, diags *diag.Diagnostics) 
[]table.Update {
-       if plan.SortOrder.IsUnknown() {
-               if tbl.SortOrder().OrderID() != 0 {
-                       // Create a new unsorted order and set it as default
-                       unsortedOrder := table.UnsortedSortOrder
-
-                       return []table.Update{
-                               table.NewAddSortOrderUpdate(&unsortedOrder),
-                               table.NewSetDefaultSortOrderUpdate(0),
-                       }
-               }
-
-               return nil
-       }
-
        if plan.SortOrder.IsNull() {
                return nil
        }
 
-       var planOrder icebergTableSortOrder
-       d := plan.SortOrder.As(ctx, &planOrder, basetypes.ObjectAsOptions{})
-       diags.Append(d...)
+       newIcebergOrder := table.UnsortedSortOrder
+       if !plan.SortOrder.IsUnknown() {
+               var planOrder icebergTableSortOrder
+               d := plan.SortOrder.As(ctx, &planOrder, 
basetypes.ObjectAsOptions{})
+               diags.Append(d...)
 
-       if diags.HasError() {
+               if diags.HasError() {
+                       return nil
+               }
+
+               order, err := planOrder.ToIceberg()
+               if err != nil {
+                       diags.AddError("failed to convert sort order", 
err.Error())
+
+                       return nil
+               }
+               newIcebergOrder = order
+       }
+
+       if sameSortFields(tbl.SortOrder(), newIcebergOrder) {
                return nil
        }
 
-       newIcebergOrder, err := planOrder.ToIceberg()
-       if err != nil {
-               diags.AddError("failed to convert sort order", err.Error())
+       // Returning to an earlier sort order: point back at its existing ID.
+       for _, existing := range tbl.Metadata().SortOrders() {
+               if sameSortFields(existing, newIcebergOrder) {
+                       return 
[]table.Update{table.NewSetDefaultSortOrderUpdate(existing.OrderID())}
+               }
+       }
 
-               return nil
+       // A new sort order: add it and make it the default.
+       return []table.Update{
+               table.NewAddSortOrderUpdate(&newIcebergOrder),
+               table.NewSetDefaultSortOrderUpdate(-1),
        }
+}
 
-       // Compare with current sort order
-       if !tbl.SortOrder().Equals(newIcebergOrder) {
-               return []table.Update{
-                       table.NewAddSortOrderUpdate(&newIcebergOrder),
-                       table.NewSetDefaultSortOrderUpdate(-1),
+// sameSortFields matches the catalog's sort order reuse rule: fields are
+// compared and the order ID is ignored.
+func sameSortFields(a, b table.SortOrder) bool {
+       if a.Len() != b.Len() {
+               return false
+       }
+       for i := range a.Len() {
+               if !a.Field(i).Equals(b.Field(i)) {
+                       return false
                }
        }
 
-       return nil
+       return true
 }
 
 func (r *icebergTableResource) syncTableToModel(ctx context.Context, tbl 
*table.Table, model *icebergTableResourceModel, diags *diag.Diagnostics) {
diff --git a/internal/provider/resource_table_test.go 
b/internal/provider/resource_table_test.go
index 30cd017..4960e15 100644
--- a/internal/provider/resource_table_test.go
+++ b/internal/provider/resource_table_test.go
@@ -15,11 +15,17 @@
 package provider
 
 import (
+       "context"
+       "encoding/json"
        "fmt"
        "os"
        "regexp"
+       "strings"
        "testing"
 
+       "github.com/apache/iceberg-go/table"
+       "github.com/hashicorp/terraform-plugin-framework/diag"
+       "github.com/hashicorp/terraform-plugin-framework/types"
        "github.com/hashicorp/terraform-plugin-testing/helper/resource"
 )
 
@@ -542,9 +548,14 @@ func TestAccIcebergTableDroppedFieldIDReuse(t *testing.T) {
                                ExpectError: regexp.MustCompile(`(?s)invalid 
field id.*belonged to dropped field "dropped"`),
                        },
                        {
-                               // Re-adding the dropped field by name doesn't 
restore its id either.
-                               Config:      
testAccIcebergTableSecondFieldConfig(providerCfg, tableName, "dropped", "2"),
-                               ExpectError: regexp.MustCompile(`(?s)invalid 
field id.*belonged to dropped field "dropped"`),
+                               // Re-declaring the dropped field exactly as it 
was is a revert to
+                               // schema 0, not a new field reusing its id.
+                               Config: 
testAccIcebergTableSecondFieldConfig(providerCfg, tableName, "dropped", "2"),
+                               Check: resource.ComposeTestCheckFunc(
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.id", "0"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.fields.1.name", 
"dropped"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.fields.1.id", "2"),
+                               ),
                        },
                        {
                                Config: 
testAccIcebergTableSecondFieldConfig(providerCfg, tableName, "replacement", ""),
@@ -1139,3 +1150,414 @@ resource "iceberg_table" "test" {
 }
 `, tableName, colName)
 }
+
+func TestAccIcebergTableRevertToExistingMetadata(t *testing.T) {
+       catalogURI := os.Getenv("ICEBERG_CATALOG_URI")
+       if catalogURI == "" {
+               catalogURI = "http://localhost:8181";
+       }
+
+       providerCfg := fmt.Sprintf(providerConfig, catalogURI)
+       tableName := "revert_test"
+
+       resource.Test(t, resource.TestCase{
+               PreCheck:                 func() { testAccPreCheck(t) },
+               ProtoV6ProviderFactories: testAccProtoV6ProviderFactories,
+               Steps: []resource.TestStep{
+                       {
+                               Config: 
testAccIcebergTableRevertConfig(providerCfg, tableName, false, "asc"),
+                               Check: resource.ComposeTestCheckFunc(
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.id", "0"),
+                                       
resource.TestCheckNoResourceAttr("iceberg_table.test", "partition_spec"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "sort_order.order_id", 
"1"),
+                               ),
+                       },
+                       {
+                               Config: 
testAccIcebergTableRevertConfig(providerCfg, tableName, true, "desc"),
+                               Check: resource.ComposeTestCheckFunc(
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.id", "1"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "partition_spec.spec_id", 
"1"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "sort_order.order_id", 
"2"),
+                               ),
+                       },
+                       {
+                               Config: 
testAccIcebergTableRevertConfig(providerCfg, tableName, false, "asc"),
+                               Check: resource.ComposeTestCheckFunc(
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.id", "0"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "schema.fields.#", "2"),
+                                       
resource.TestCheckNoResourceAttr("iceberg_table.test", "partition_spec"),
+                                       
resource.TestCheckResourceAttr("iceberg_table.test", "sort_order.order_id", 
"1"),
+                               ),
+                       },
+               },
+       })
+}
+
+func testAccIcebergTableRevertConfig(providerCfg, tableName string, evolved 
bool, sortDirection string) string {
+       extraField, partitionSpec := "", ""
+       if evolved {
+               extraField = `,
+      {
+        name     = "b"
+        type     = "string"
+        required = false
+      }`
+               partitionSpec = `
+  partition_spec = {
+    fields = [
+      {
+        source_ids = [2]
+        name       = "ts_day"
+        transform  = "day"
+      }
+    ]
+  }`
+       }
+
+       return providerCfg + fmt.Sprintf(`
+resource "iceberg_namespace" "db_revert" {
+  name = ["db_revert"]
+}
+
+resource "iceberg_table" "test" {
+  namespace = iceberg_namespace.db_revert.name
+  name      = "%s"
+  schema = {
+    fields = [
+      {
+        name     = "id"
+        type     = "long"
+        required = true
+      },
+      {
+        name     = "ts"
+        type     = "timestamp"
+        required = false
+      }%s
+    ]
+  }%s
+  sort_order = {
+    fields = [
+      {
+        source_id  = 1
+        transform  = "identity"
+        direction  = "%s"
+        null_order = "nulls-first"
+      }
+    ]
+  }
+}
+`, tableName, extraField, partitionSpec, sortDirection)
+}
+
+// historyMetadata is a table whose current schema, spec, and sort order are
+// the last of several, so the earlier ones can be returned to.
+const historyMetadata = `{
+  "format-version": 2,
+  "table-uuid": "9c12d441-03fe-4693-9a96-a0705ddf69c1",
+  "location": "s3://bucket/t",
+  "last-sequence-number": 0,
+  "last-updated-ms": 1602638573590,
+  "last-column-id": 3,
+  "current-schema-id": 1,
+  "schemas": [
+    {"type": "struct", "schema-id": 0, "fields": [
+      {"id": 1, "name": "id", "required": true, "type": "long"},
+      {"id": 2, "name": "ts", "required": false, "type": "timestamp"}
+    ]},
+    {"type": "struct", "schema-id": 1, "fields": [
+      {"id": 1, "name": "id", "required": true, "type": "long"},
+      {"id": 2, "name": "ts", "required": false, "type": "timestamp"},
+      {"id": 3, "name": "b", "required": false, "type": "string"}
+    ]}
+  ],
+  "default-spec-id": 1,
+  "partition-specs": [
+    {"spec-id": 0, "fields": []},
+    {"spec-id": 1, "fields": [{"source-id": 2, "field-id": 1000, "name": 
"ts_day", "transform": "day"}]}
+  ],
+  "last-partition-id": 1000,
+  "default-sort-order-id": 2,
+  "sort-orders": [
+    {"order-id": 0, "fields": []},
+    {"order-id": 1, "fields": [{"source-id": 1, "transform": "identity", 
"direction": "asc", "null-order": "nulls-first"}]},
+    {"order-id": 2, "fields": [{"source-id": 1, "transform": "identity", 
"direction": "desc", "null-order": "nulls-last"}]}
+  ],
+  "properties": {},
+  "snapshots": [],
+  "snapshot-log": [],
+  "metadata-log": []
+}`
+
+func historyTable(t *testing.T) *table.Table {
+       t.Helper()
+       meta, err := table.ParseMetadataString(historyMetadata)
+       if err != nil {
+               t.Fatalf("parse metadata: %v", err)
+       }
+
+       return table.New(table.Identifier{"db", "t"}, meta, 
"s3://bucket/t/metadata/v1.json", nil, nil)
+}
+
+func objectFromJSON[T any](t *testing.T, attrTypes func(T) types.Object, raw 
string) types.Object {
+       t.Helper()
+       var v T
+       if err := json.Unmarshal([]byte(raw), &v); err != nil {
+               t.Fatalf("unmarshal %s: %v", raw, err)
+       }
+
+       return attrTypes(v)
+}
+
+func schemaObject(t *testing.T, raw string) types.Object {
+       return objectFromJSON(t, func(s icebergTableSchema) types.Object {
+               obj, d := types.ObjectValueFrom(context.Background(), 
icebergTableSchema{}.AttrTypes(), s)
+               if d.HasError() {
+                       t.Fatalf("schema object: %v", d)
+               }
+
+               return obj
+       }, raw)
+}
+
+func specObject(t *testing.T, raw string) types.Object {
+       return objectFromJSON(t, func(s icebergTablePartitionSpec) types.Object 
{
+               s.SpecID = types.Int64Unknown()
+               obj, d := types.ObjectValueFrom(context.Background(), 
icebergTablePartitionSpec{}.AttrTypes(), s)
+               if d.HasError() {
+                       t.Fatalf("spec object: %v", d)
+               }
+
+               return obj
+       }, raw)
+}
+
+func sortObject(t *testing.T, raw string) types.Object {
+       return objectFromJSON(t, func(s icebergTableSortOrder) types.Object {
+               s.OrderID = types.Int64Unknown()
+               obj, d := types.ObjectValueFrom(context.Background(), 
icebergTableSortOrder{}.AttrTypes(), s)
+               if d.HasError() {
+                       t.Fatalf("sort order object: %v", d)
+               }
+
+               return obj
+       }, raw)
+}
+
+func updateActions(t *testing.T, updates []table.Update) string {
+       t.Helper()
+       b, err := json.Marshal(updates)
+       if err != nil {
+               t.Fatalf("marshal updates: %v", err)
+       }
+       var raw []map[string]any
+       if err := json.Unmarshal(b, &raw); err != nil {
+               t.Fatalf("unmarshal updates: %v", err)
+       }
+       var out strings.Builder
+       for _, u := range raw {
+               out.WriteString(u["action"].(string))
+               if s, ok := u["schema"].(map[string]any); ok {
+                       b, _ := json.Marshal(s["schema-id"])
+                       fmt.Fprintf(&out, "(%s)", b)
+               }
+               for _, k := range []string{"schema-id", "spec-id", 
"sort-order-id"} {
+                       if v, ok := u[k]; ok {
+                               b, _ := json.Marshal(v)
+                               fmt.Fprintf(&out, "(%s)", b)
+                       }
+               }
+               out.WriteString(";")
+       }
+
+       return out.String()
+}
+
+const (
+       // schemaV0 has schema 0's fields but the current schema's ID, as a real
+       // plan would, so matching an existing schema must ignore the ID.
+       schemaV0 = `{"schema-id": 1, "fields": [
+  {"id": 1, "name": "id", "required": true, "type": "long"},
+  {"id": 2, "name": "ts", "required": false, "type": "timestamp"}]}`
+       schemaV1 = `{"schema-id": 1, "fields": [
+  {"id": 1, "name": "id", "required": true, "type": "long"},
+  {"id": 2, "name": "ts", "required": false, "type": "timestamp"},
+  {"id": 3, "name": "b", "required": false, "type": "string"}]}`
+       schemaNew = `{"schema-id": 1, "fields": [
+  {"id": 1, "name": "id", "required": true, "type": "long"},
+  {"id": 2, "name": "ts", "required": false, "type": "timestamp"},
+  {"id": 4, "name": "c", "required": false, "type": "string"}]}`
+)
+
+func TestCalculateSchemaUpdatesReusesExistingSchema(t *testing.T) {
+       tbl := historyTable(t)
+       r := &icebergTableResource{}
+
+       cases := map[string]struct {
+               plan string
+               want string
+       }{
+               "unchanged":            {plan: schemaV1, want: ""},
+               "revert to schema 0":   {plan: schemaV0, want: 
"set-current-schema(0);"},
+               "genuinely new schema": {plan: schemaNew, want: 
"add-schema(2);set-current-schema(2);"},
+       }
+
+       for name, tc := range cases {
+               t.Run(name, func(t *testing.T) {
+                       var diags diag.Diagnostics
+                       plan := &icebergTableResourceModel{Schema: 
schemaObject(t, tc.plan)}
+                       state := &icebergTableResourceModel{Schema: 
schemaObject(t, schemaV1)}
+                       got := updateActions(t, 
r.calculateSchemaUpdates(context.Background(), plan, state, tbl, &diags))
+                       if diags.HasError() {
+                               t.Fatalf("unexpected diagnostics: %v", diags)
+                       }
+                       if got != tc.want {
+                               t.Errorf("updates = %q, want %q", got, tc.want)
+                       }
+               })
+       }
+}
+
+// Reverting to an earlier schema is still an evolution from the current one,
+// so undoing a type promotion must be rejected rather than reusing the old ID.
+func TestCalculateSchemaUpdatesRejectsRevertingPromotion(t *testing.T) {
+       // Make schema 0's "id" an int, so schema 1 (current) promoted it to 
long.
+       promoted := strings.Replace(historyMetadata, `"type": "long"`, `"type": 
"int"`, 1)
+       meta, err := table.ParseMetadataString(promoted)
+       if err != nil {
+               t.Fatalf("parse metadata: %v", err)
+       }
+       tbl := table.New(table.Identifier{"db", "t"}, meta, 
"s3://bucket/t/metadata/v1.json", nil, nil)
+
+       revert := strings.Replace(schemaV0, `"type": "long"`, `"type": "int"`, 
1)
+       var diags diag.Diagnostics
+       plan := &icebergTableResourceModel{Schema: schemaObject(t, revert)}
+       state := &icebergTableResourceModel{Schema: schemaObject(t, schemaV1)}
+       updates := 
(&icebergTableResource{}).calculateSchemaUpdates(context.Background(), plan, 
state, tbl, &diags)
+       if !diags.HasError() {
+               t.Fatalf("expected an invalid schema evolution error, got 
updates %q", updateActions(t, updates))
+       }
+}
+
+// Returning to a schema that had a since-dropped field re-declares that field
+// with its old ID. That is an exact match for an existing schema, so it must
+// reuse that schema rather than be rejected as dropped field ID reuse.
+func TestCalculateSchemaUpdatesRevertsPastDroppedField(t *testing.T) {
+       // Make schema 0 current, so schema 1's "b" (id 3) is a dropped field.
+       dropped := strings.Replace(historyMetadata, `"current-schema-id": 1`, 
`"current-schema-id": 0`, 1)
+       meta, err := table.ParseMetadataString(dropped)
+       if err != nil {
+               t.Fatalf("parse metadata: %v", err)
+       }
+       tbl := table.New(table.Identifier{"db", "t"}, meta, 
"s3://bucket/t/metadata/v1.json", nil, nil)
+       r := &icebergTableResource{}
+
+       cases := map[string]struct {
+               plan    string
+               want    string
+               wantErr bool
+       }{
+               "exact revert re-declaring dropped id": {plan: schemaV1, want: 
"set-current-schema(1);"},
+               "new schema reusing dropped id": {plan: `{"schema-id": 0, 
"fields": [
+  {"id": 1, "name": "id", "required": true, "type": "long"},
+  {"id": 2, "name": "ts", "required": false, "type": "timestamp"},
+  {"id": 3, "name": "renamed_b", "required": false, "type": "string"}]}`, 
wantErr: true},
+       }
+
+       for name, tc := range cases {
+               t.Run(name, func(t *testing.T) {
+                       var diags diag.Diagnostics
+                       plan := &icebergTableResourceModel{Schema: 
schemaObject(t, tc.plan)}
+                       state := &icebergTableResourceModel{Schema: 
schemaObject(t, schemaV0)}
+                       got := updateActions(t, 
r.calculateSchemaUpdates(context.Background(), plan, state, tbl, &diags))
+                       if diags.HasError() != tc.wantErr {
+                               t.Fatalf("diagnostics = %v, wantErr %v", diags, 
tc.wantErr)
+                       }
+                       if got != tc.want {
+                               t.Errorf("updates = %q, want %q", got, tc.want)
+                       }
+               })
+       }
+}
+
+func TestCalculatePartitionUpdatesReusesExistingSpec(t *testing.T) {
+       tbl := historyTable(t)
+       r := &icebergTableResource{}
+
+       cases := map[string]struct {
+               plan types.Object
+               want string
+       }{
+               "unchanged": {
+                       plan: specObject(t, `{"fields": [{"source-ids": [2], 
"name": "ts_day", "transform": "day"}]}`),
+                       want: "",
+               },
+               "removed from config": {
+                       plan: 
types.ObjectUnknown(icebergTablePartitionSpec{}.AttrTypes()),
+                       want: "set-default-spec(0);",
+               },
+               "explicitly empty": {
+                       plan: specObject(t, `{"fields": []}`),
+                       want: "set-default-spec(0);",
+               },
+               "genuinely new spec": {
+                       plan: specObject(t, `{"fields": [{"source-ids": [1], 
"name": "id_b", "transform": "bucket[4]"}]}`),
+                       want: "add-spec;set-default-spec(-1);",
+               },
+       }
+
+       for name, tc := range cases {
+               t.Run(name, func(t *testing.T) {
+                       var diags diag.Diagnostics
+                       plan := &icebergTableResourceModel{PartitionSpec: 
tc.plan}
+                       got := updateActions(t, 
r.calculatePartitionUpdates(context.Background(), plan, tbl, &diags))
+                       if diags.HasError() {
+                               t.Fatalf("unexpected diagnostics: %v", diags)
+                       }
+                       if got != tc.want {
+                               t.Errorf("updates = %q, want %q", got, tc.want)
+                       }
+               })
+       }
+}
+
+func TestCalculateSortOrderUpdatesReusesExistingOrder(t *testing.T) {
+       tbl := historyTable(t)
+       r := &icebergTableResource{}
+
+       cases := map[string]struct {
+               plan types.Object
+               want string
+       }{
+               "unchanged with unknown order id": {
+                       plan: sortObject(t, `{"fields": [{"source-id": 1, 
"transform": "identity", "direction": "desc", "null-order": "nulls-last"}]}`),
+                       want: "",
+               },
+               "revert to order 1": {
+                       plan: sortObject(t, `{"fields": [{"source-id": 1, 
"transform": "identity", "direction": "asc", "null-order": "nulls-first"}]}`),
+                       want: "set-default-sort-order(1);",
+               },
+               "removed from config": {
+                       plan: 
types.ObjectUnknown(icebergTableSortOrder{}.AttrTypes()),
+                       want: "set-default-sort-order(0);",
+               },
+               "genuinely new order": {
+                       plan: sortObject(t, `{"fields": [{"source-id": 2, 
"transform": "identity", "direction": "asc", "null-order": "nulls-first"}]}`),
+                       want: "add-sort-order;set-default-sort-order(-1);",
+               },
+       }
+
+       for name, tc := range cases {
+               t.Run(name, func(t *testing.T) {
+                       var diags diag.Diagnostics
+                       plan := &icebergTableResourceModel{SortOrder: tc.plan}
+                       got := updateActions(t, 
r.calculateSortOrderUpdates(context.Background(), plan, tbl, &diags))
+                       if diags.HasError() {
+                               t.Fatalf("unexpected diagnostics: %v", diags)
+                       }
+                       if got != tc.want {
+                               t.Errorf("updates = %q, want %q", got, tc.want)
+                       }
+               })
+       }
+}

Reply via email to