Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
68 changes: 68 additions & 0 deletions table/update_schema_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2982,3 +2982,71 @@ func TestAddFilesAfterAddColumnReadsNewColumnByName(t *testing.T) {
require.False(t, category.IsNull(0), "category was read as null")
assert.Equal(t, "books", category.Value(0))
}

// A decimal default added by AddColumn must survive the metadata JSON round
// trip, so files written before the column existed still read the default
// after the table is reloaded.
func TestAddColumnDecimalDefaultSurvivesMetadataRoundTrip(t *testing.T) {
ctx := context.Background()
dir := filepath.ToSlash(t.TempDir())
schema := iceberg.NewSchema(0,
iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int32, Required: true})
meta, err := NewMetadata(schema, iceberg.UnpartitionedSpec, UnsortedSortOrder, dir,
iceberg.Properties{PropertyFormatVersion: "3"})
require.NoError(t, err)
fsF := func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }
tbl := New(Identifier{"default", "decimal_default"}, meta, dir+"/metadata/00000.json", fsF,
&countingCatalog{metadata: meta})

// A file written before the price column exists.
arrSchema := arrow.NewSchema([]arrow.Field{{Name: "id", Type: arrow.PrimitiveTypes.Int32}}, nil)
ids := array.NewInt32Builder(memory.DefaultAllocator)
defer ids.Release()
ids.AppendValues([]int32{1}, nil)
idArr := ids.NewArray()
defer idArr.Release()
rec := array.NewRecordBatch(arrSchema, []arrow.Array{idArr}, 1)
defer rec.Release()
arrTbl := array.NewTableFromRecords(arrSchema, []arrow.RecordBatch{rec})
defer arrTbl.Release()
path := dir + "/data/before.parquet"
fo, err := iceio.LocalFS{}.Create(ctx, path)
require.NoError(t, err)
require.NoError(t, pqarrow.WriteTable(arrTbl, fo, arrTbl.NumRows(), nil, pqarrow.DefaultWriterProps()))

txn := tbl.NewTransaction()
require.NoError(t, txn.AddDataFilesByPath(ctx, []string{path}, nil, false))
tbl, err = txn.Commit(ctx)
require.NoError(t, err)

decimalType := iceberg.MustDecimalTypeOf(9, 2)
price, err := iceberg.NewLiteral("14.20").To(decimalType)
require.NoError(t, err)
txn = tbl.NewTransaction()
require.NoError(t, txn.UpdateSchema(true, false).
AddColumn([]string{"price"}, decimalType, "", false, price).
Commit())
tbl, err = txn.Commit(ctx)
require.NoError(t, err)

// Reload the table from its metadata JSON, as a catalog would.
metaJSON, err := json.Marshal(tbl.Metadata())
require.NoError(t, err)
reloaded, err := ParseMetadataBytes(metaJSON)
require.NoError(t, err)
field, ok := reloaded.CurrentSchema().FindFieldByName("price")
require.True(t, ok)
assert.Equal(t, "14.20", field.InitialDefault)
assert.Equal(t, "14.20", field.WriteDefault)

tbl = New(Identifier{"default", "decimal_default"}, reloaded, dir+"/metadata/00002.json", fsF,
&countingCatalog{metadata: reloaded})
result, err := tbl.Scan().ToArrowTable(ctx)
require.NoError(t, err)
defer result.Release()

require.EqualValues(t, 1, result.NumRows())
prices := result.Column(result.Schema().FieldIndices("price")[0]).Data().Chunk(0).(*array.Decimal128)
require.False(t, prices.IsNull(0))
assert.Equal(t, "14.20", prices.Value(0).ToString(2))
}
6 changes: 6 additions & 0 deletions types.go
Original file line number Diff line number Diff line change
Expand Up @@ -372,6 +372,12 @@ func defaultValueToJSON(typ Type, value any) any {
if encoded, ok := hexDefault(typ, value); ok {
return encoded
}
// Decimal has no JSON encoding of its own, and its decimal128 value has no
// exported fields, so it would be written as {"Val":{},"Scale":2} and lose
// the value. Write the spec's single-value form, a string such as "14.20".
if d, ok := value.(Decimal); ok {
return d.String()
}

return value
}
Expand Down
30 changes: 30 additions & 0 deletions types_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -932,6 +932,36 @@ func TestNestedFieldMarshalBinaryDefaultsAsHex(t *testing.T) {
}
}

// A decimal default must be written as its string form, as the spec's JSON
// single-value serialization and Java's SingleValueParser require. Decimal
// has no JSON encoding of its own, so it used to be written as
// {"Val":{},"Scale":2}, which loses the value.
func TestNestedFieldMarshalDecimalDefaultsAsString(t *testing.T) {
typ := iceberg.MustDecimalTypeOf(9, 2)
lit, err := iceberg.NewLiteral("14.20").To(typ)
require.NoError(t, err)
negative, err := iceberg.NewLiteral("-0.05").To(typ)
require.NoError(t, err)

field := iceberg.NestedField{
ID: 1, Name: "price", Type: typ,
// AddColumn stores a default literal's Any(), which is an iceberg.Decimal.
InitialDefault: lit.Any(),
WriteDefault: negative.Any(),
}

actual, err := json.Marshal(field)
require.NoError(t, err)
assert.JSONEq(t,
`{"id":1,"name":"price","required":false,"initial-default":"14.20","write-default":"-0.05","type":"decimal(9, 2)"}`,
string(actual))

var decoded iceberg.NestedField
require.NoError(t, json.Unmarshal(actual, &decoded))
assert.Equal(t, "14.20", decoded.InitialDefault)
assert.Equal(t, "-0.05", decoded.WriteDefault)
}

func TestTypeIFaceMarshalJSONNilType(t *testing.T) {
// A NestedField with a nil Type must not panic during JSON marshalling.
// Prior to this fix, typeIFace.MarshalJSON called t.Type.Type() on a nil
Expand Down
Loading