slachiewicz commented on code in PR #2487: URL: https://github.com/apache/iceberg-go/pull/2487#discussion_r4729000928
########## table/identity_partition_projection_internal_test.go: ########## @@ -0,0 +1,472 @@ +// 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 table + +import ( + "context" + "fmt" + "iter" + "os" + "path/filepath" + "sort" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/decimal128" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/arrow-go/v18/parquet/pqarrow" + "github.com/apache/iceberg-go" + iceio "github.com/apache/iceberg-go/io" + "github.com/stretchr/testify/require" +) + +// A writer may leave an identity partition column out of its data files, as +// Delta and Hive-style layouts do. The spec's column projection reads such a +// field from the file's partition value (rule 1), required or not. +func TestScanFillsIdentityPartitionColumnMissingFromDataFile(t *testing.T) { + ctx := context.Background() + location := filepath.ToSlash(t.TempDir()) + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "region", Type: iceberg.PrimitiveTypes.String, Required: true}, + ) + spec := iceberg.NewPartitionSpec(iceberg.PartitionField{ + SourceIDs: []int{2}, FieldID: 1000, Name: "region", Transform: iceberg.IdentityTransform{}, + }) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, nil) + require.NoError(t, err) + tbl := New(Identifier{"db", "identity"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) + + // Each file stores only id; its region lives in the manifest. + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + files := make([]iceberg.DataFile, 0, 2) + for _, part := range []struct { + region string + ids string + }{{"east", `[{"id":1},{"id":2}]`}, {"west", `[{"id":3}]`}} { + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{part.ids}) + require.NoError(t, err) + path := location + "/data/" + part.region + ".parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + b, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, path, iceberg.ParquetFile, + map[int]any{1000: part.region}, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + files = append(files, b.Build()) + data.Release() + } + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(ctx, files, nil)) + tbl, err = txn.Commit(ctx) + require.NoError(t, err) + + result, err := tbl.Scan().ToArrowTable(ctx) + require.NoError(t, err) + defer result.Release() + + got := map[int64]string{} + reader := array.NewTableReader(result, -1) + defer reader.Release() + for reader.Next() { + rec := reader.RecordBatch() + ids := rec.Column(0).(*array.Int64) + regions := rec.Column(1).(*array.String) + for i := range int(rec.NumRows()) { + got[ids.Value(i)] = regions.Value(i) + } + } + require.Equal(t, map[int64]string{1: "east", 2: "east", 3: "west"}, got) + + // A filter on the partition column prunes by it and still fills it. + filtered, err := tbl.Scan(WithRowFilter(iceberg.EqualTo(iceberg.Reference("region"), "west"))).ToArrowTable(ctx) + require.NoError(t, err) + defer filtered.Release() + require.EqualValues(t, 1, filtered.NumRows()) +} + +// Partition values come back from the manifest as literals; a decimal one +// must still fill the column rather than fail the scan. +func TestScanFillsDecimalIdentityPartitionColumnMissingFromDataFile(t *testing.T) { + ctx := context.Background() + location := filepath.ToSlash(t.TempDir()) + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "amount", Type: iceberg.MustDecimalTypeOf(9, 2)}, + ) + spec := iceberg.NewPartitionSpec(iceberg.PartitionField{ + SourceIDs: []int{2}, FieldID: 1000, Name: "amount", Transform: iceberg.IdentityTransform{}, + }) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, nil) + require.NoError(t, err) + tbl := New(Identifier{"db", "identity_decimal"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) + + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{`[{"id":1},{"id":2}]`}) + require.NoError(t, err) + defer data.Release() + path := location + "/data/amount.parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + value := iceberg.Decimal{Val: decimal128.FromI64(1234), Scale: 2} + b, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, path, iceberg.ParquetFile, + map[int]any{1000: value}, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(ctx, []iceberg.DataFile{b.Build()}, nil)) + tbl, err = txn.Commit(ctx) + require.NoError(t, err) + + result, err := tbl.Scan().ToArrowTable(ctx) + require.NoError(t, err) + defer result.Release() + require.EqualValues(t, 2, result.NumRows()) + for _, chunk := range result.Column(1).Data().Chunks() { + amounts := chunk.(*array.Decimal128) + for i := range amounts.Len() { + require.False(t, amounts.IsNull(i)) + require.Equal(t, "12.34", amounts.ValueStr(i)) + } + } +} + +// identityPartitionTestTable returns an empty table at a fresh location. +func identityPartitionTestTable(t *testing.T, schema *iceberg.Schema, spec iceberg.PartitionSpec, props iceberg.Properties) *Table { + t.Helper() + + location := filepath.ToSlash(t.TempDir()) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, props) + require.NoError(t, err) + + return New(Identifier{"db", "identity"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) +} + +// addIDOnlyFile commits a data file that stores only the id column (field ID +// 1), with partition as its partition data under the table's current spec. +func addIDOnlyFile(t *testing.T, tbl *Table, name string, partition map[int]any, ids string) *Table { + t.Helper() + + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{ids}) + require.NoError(t, err) + defer data.Release() + + path := tbl.Location() + "/data/" + name + ".parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + b, err := iceberg.NewDataFileBuilder(tbl.Spec(), iceberg.EntryContentData, path, iceberg.ParquetFile, + partition, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + if tbl.Metadata().FormatVersion() >= 3 { + b.FirstRowID(tbl.Metadata().NextRowID()) + } + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(t.Context(), []iceberg.DataFile{b.Build()}, nil)) + tbl, err = txn.Commit(t.Context()) + require.NoError(t, err) + + return tbl +} + +// scanIDAndColumn returns each row of a two-column (id, value) scan as +// "id:value", sorted, with "id:<null>" for a null value. +func scanIDAndColumn(t *testing.T, tbl *Table, opts ...ScanOption) []string { + t.Helper() + + _, records, err := tbl.Scan(opts...).ToArrowRecords(t.Context()) + require.NoError(t, err) + + return idAndColumnRows(t, records) +} + +// idAndColumnRows formats each row of two-column (id, value) records as +// "id:value", sorted, with "id:<null>" for a null value. +func idAndColumnRows(t *testing.T, records iter.Seq2[arrow.RecordBatch, error]) []string { + t.Helper() + + rows := []string{} + for rec, err := range records { + require.NoError(t, err) + ids := rec.Column(0).(*array.Int64) + for i := range int(rec.NumRows()) { + value := "<null>" + if !rec.Column(1).IsNull(i) { + value = rec.Column(1).ValueStr(i) + } + rows = append(rows, fmt.Sprintf("%d:%s", ids.Value(i), value)) + } + rec.Release() + } + sort.Strings(rows) + + return rows +} + +// regionTestTable has id 1 in both partitions, in files that store only id. +func regionTestTable(t *testing.T, props iceberg.Properties) *Table { + t.Helper() + + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "region", Type: iceberg.PrimitiveTypes.String, Required: true}, + ) + spec := iceberg.NewPartitionSpec(iceberg.PartitionField{ + SourceIDs: []int{2}, FieldID: 1000, Name: "region", Transform: iceberg.IdentityTransform{}, + }) + tbl := identityPartitionTestTable(t, schema, spec, props) + tbl = addIDOnlyFile(t, tbl, "east", map[int]any{1000: "east"}, `[{"id":1},{"id":2}]`) + + return addIDOnlyFile(t, tbl, "west", map[int]any{1000: "west"}, `[{"id":1},{"id":3}]`) +} Review Comment: Done in a9c1fa4: `regionTestTable` adds both files in one `AddDataFiles` commit, and the delete test runs v2 and v3, copy-on-write and merge-on-read, with `west` and `east`. 737b0d6 adds a case whose v3 copy-on-write run fails with the row-group fold disabled. ########## table/identity_partition_projection_internal_test.go: ########## @@ -0,0 +1,472 @@ +// 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 table + +import ( + "context" + "fmt" + "iter" + "os" + "path/filepath" + "sort" + "testing" + + "github.com/apache/arrow-go/v18/arrow" + "github.com/apache/arrow-go/v18/arrow/array" + "github.com/apache/arrow-go/v18/arrow/decimal128" + "github.com/apache/arrow-go/v18/arrow/memory" + "github.com/apache/arrow-go/v18/parquet/pqarrow" + "github.com/apache/iceberg-go" + iceio "github.com/apache/iceberg-go/io" + "github.com/stretchr/testify/require" +) + +// A writer may leave an identity partition column out of its data files, as +// Delta and Hive-style layouts do. The spec's column projection reads such a +// field from the file's partition value (rule 1), required or not. +func TestScanFillsIdentityPartitionColumnMissingFromDataFile(t *testing.T) { + ctx := context.Background() + location := filepath.ToSlash(t.TempDir()) + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "region", Type: iceberg.PrimitiveTypes.String, Required: true}, + ) + spec := iceberg.NewPartitionSpec(iceberg.PartitionField{ + SourceIDs: []int{2}, FieldID: 1000, Name: "region", Transform: iceberg.IdentityTransform{}, + }) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, nil) + require.NoError(t, err) + tbl := New(Identifier{"db", "identity"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) + + // Each file stores only id; its region lives in the manifest. + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + files := make([]iceberg.DataFile, 0, 2) + for _, part := range []struct { + region string + ids string + }{{"east", `[{"id":1},{"id":2}]`}, {"west", `[{"id":3}]`}} { + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{part.ids}) + require.NoError(t, err) + path := location + "/data/" + part.region + ".parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + b, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, path, iceberg.ParquetFile, + map[int]any{1000: part.region}, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + files = append(files, b.Build()) + data.Release() + } + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(ctx, files, nil)) + tbl, err = txn.Commit(ctx) + require.NoError(t, err) + + result, err := tbl.Scan().ToArrowTable(ctx) + require.NoError(t, err) + defer result.Release() + + got := map[int64]string{} + reader := array.NewTableReader(result, -1) + defer reader.Release() + for reader.Next() { + rec := reader.RecordBatch() + ids := rec.Column(0).(*array.Int64) + regions := rec.Column(1).(*array.String) + for i := range int(rec.NumRows()) { + got[ids.Value(i)] = regions.Value(i) + } + } + require.Equal(t, map[int64]string{1: "east", 2: "east", 3: "west"}, got) + + // A filter on the partition column prunes by it and still fills it. + filtered, err := tbl.Scan(WithRowFilter(iceberg.EqualTo(iceberg.Reference("region"), "west"))).ToArrowTable(ctx) + require.NoError(t, err) + defer filtered.Release() + require.EqualValues(t, 1, filtered.NumRows()) +} + +// Partition values come back from the manifest as literals; a decimal one +// must still fill the column rather than fail the scan. +func TestScanFillsDecimalIdentityPartitionColumnMissingFromDataFile(t *testing.T) { + ctx := context.Background() + location := filepath.ToSlash(t.TempDir()) + schema := iceberg.NewSchema(0, + iceberg.NestedField{ID: 1, Name: "id", Type: iceberg.PrimitiveTypes.Int64, Required: true}, + iceberg.NestedField{ID: 2, Name: "amount", Type: iceberg.MustDecimalTypeOf(9, 2)}, + ) + spec := iceberg.NewPartitionSpec(iceberg.PartitionField{ + SourceIDs: []int{2}, FieldID: 1000, Name: "amount", Transform: iceberg.IdentityTransform{}, + }) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, nil) + require.NoError(t, err) + tbl := New(Identifier{"db", "identity_decimal"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) + + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{`[{"id":1},{"id":2}]`}) + require.NoError(t, err) + defer data.Release() + path := location + "/data/amount.parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + value := iceberg.Decimal{Val: decimal128.FromI64(1234), Scale: 2} + b, err := iceberg.NewDataFileBuilder(spec, iceberg.EntryContentData, path, iceberg.ParquetFile, + map[int]any{1000: value}, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(ctx, []iceberg.DataFile{b.Build()}, nil)) + tbl, err = txn.Commit(ctx) + require.NoError(t, err) + + result, err := tbl.Scan().ToArrowTable(ctx) + require.NoError(t, err) + defer result.Release() + require.EqualValues(t, 2, result.NumRows()) + for _, chunk := range result.Column(1).Data().Chunks() { + amounts := chunk.(*array.Decimal128) + for i := range amounts.Len() { + require.False(t, amounts.IsNull(i)) + require.Equal(t, "12.34", amounts.ValueStr(i)) + } + } +} + +// identityPartitionTestTable returns an empty table at a fresh location. +func identityPartitionTestTable(t *testing.T, schema *iceberg.Schema, spec iceberg.PartitionSpec, props iceberg.Properties) *Table { + t.Helper() + + location := filepath.ToSlash(t.TempDir()) + meta, err := NewMetadata(schema, &spec, UnsortedSortOrder, location, props) + require.NoError(t, err) + + return New(Identifier{"db", "identity"}, meta, location+"/metadata/v1.metadata.json", + func(context.Context) (iceio.IO, error) { return iceio.LocalFS{}, nil }, &countingCatalog{metadata: meta}) +} + +// addIDOnlyFile commits a data file that stores only the id column (field ID +// 1), with partition as its partition data under the table's current spec. +func addIDOnlyFile(t *testing.T, tbl *Table, name string, partition map[int]any, ids string) *Table { + t.Helper() + + idOnly := arrow.NewSchema([]arrow.Field{{ + Name: "id", Type: arrow.PrimitiveTypes.Int64, + Metadata: arrow.NewMetadata([]string{ArrowParquetFieldIDKey}, []string{"1"}), + }}, nil) + data, err := array.TableFromJSON(memory.DefaultAllocator, idOnly, []string{ids}) + require.NoError(t, err) + defer data.Release() + + path := tbl.Location() + "/data/" + name + ".parquet" + require.NoError(t, os.MkdirAll(filepath.Dir(path), 0o755)) + f, err := os.Create(path) + require.NoError(t, err) + require.NoError(t, pqarrow.WriteTable(data, f, 1024, nil, pqarrow.DefaultWriterProps())) + info, err := os.Stat(path) + require.NoError(t, err) + + b, err := iceberg.NewDataFileBuilder(tbl.Spec(), iceberg.EntryContentData, path, iceberg.ParquetFile, + partition, nil, nil, data.NumRows(), info.Size()) + require.NoError(t, err) + if tbl.Metadata().FormatVersion() >= 3 { + b.FirstRowID(tbl.Metadata().NextRowID()) + } + txn := tbl.NewTransaction() + require.NoError(t, txn.AddDataFiles(t.Context(), []iceberg.DataFile{b.Build()}, nil)) + tbl, err = txn.Commit(t.Context()) + require.NoError(t, err) + + return tbl +} + +// scanIDAndColumn returns each row of a two-column (id, value) scan as +// "id:value", sorted, with "id:<null>" for a null value. +func scanIDAndColumn(t *testing.T, tbl *Table, opts ...ScanOption) []string { + t.Helper() + + _, records, err := tbl.Scan(opts...).ToArrowRecords(t.Context()) + require.NoError(t, err) + + return idAndColumnRows(t, records) Review Comment: Done in 0a9ff1c: `idAndColumnRows` checks each record column's type against the returned schema. ########## table/arrow_utils.go: ########## @@ -1276,7 +1280,17 @@ func (a *arrowProjectionVisitor) Struct(st iceberg.StructType, structArr arrow.A dt := a.typeToArrowType(field.Type) alloc := compute.GetAllocator(a.ctx) + constant, hasConstant := a.partitionConstants[field.ID] switch { + case hasConstant && constant != nil: + // Widen a value written before the field was promoted. A value + // the conversion does not cover is used as the manifest gave it. + if converted, err := identityPartitionValue(constant, field.Type); err == nil { Review Comment: Done in 58d4e3c: `convertPartitionConstants` returns the conversion error with the column name. Converting once per file is #2755. ########## table/arrow_utils.go: ########## @@ -1276,7 +1280,17 @@ func (a *arrowProjectionVisitor) Struct(st iceberg.StructType, structArr arrow.A dt := a.typeToArrowType(field.Type) alloc := compute.GetAllocator(a.ctx) + constant, hasConstant := a.partitionConstants[field.ID] switch { + case hasConstant && constant != nil: + // Widen a value written before the field was promoted. A value + // the conversion does not cover is used as the manifest gave it. + if converted, err := identityPartitionValue(constant, field.Type); err == nil { + constant = converted + } + arr = defaultToArray(constant, field.Type, dt, structArr.Len(), alloc) + case hasConstant: Review Comment: Done in 58d4e3c: a null partition value on a required field falls through to the missing-required error, as on `main`. -- This is an automated message from the Apache Git Service. To respond to the message, please log on to GitHub and use the URL above to go to the specific comment. To unsubscribe, e-mail: [email protected] For queries about this service, please contact Infrastructure at: [email protected] --------------------------------------------------------------------- To unsubscribe, e-mail: [email protected] For additional commands, e-mail: [email protected]
