This is an automated email from the ASF dual-hosted git repository.
laskoviymishka pushed a commit to branch main
in repository https://gitbox.apache.org/repos/asf/iceberg-go.git
The following commit(s) were added to refs/heads/main by this push:
new 2915ccd3d refactor(table): move helpers shared with the inspect files
into table/internal (#2614)
2915ccd3d is described below
commit 2915ccd3dc30050e2c7b935a4140ca137c1a0f3f
Author: Revanth <[email protected]>
AuthorDate: Tue Nov 17 10:53:08 2026 -0600
refactor(table): move helpers shared with the inspect files into
table/internal (#2614)
---
table/arrow_scanner.go | 58 +--------
table/arrow_scanner_posdelete_bench_test.go | 4 +-
table/arrow_scanner_posdelete_regression_test.go | 2 +-
table/arrow_utils.go | 4 -
table/clustered_writer.go | 5 +-
table/equality_delete_index.go | 3 +-
table/inspect_all_manifests.go | 7 +-
table/inspect_content_file_builder.go | 16 +--
table/inspect_entries.go | 3 +-
table/inspect_files.go | 5 +-
table/inspect_internal_test.go | 27 ++---
table/inspect_partitions.go | 130 +++++++++++----------
table/inspect_partitions_batch_test.go | 33 +++---
table/inspect_partitions_bench_test.go | 41 +++----
table/inspect_partitions_parallel_test.go | 31 ++---
table/inspect_position_deletes.go | 18 +--
table/{ => internal}/partition_aggregate.go | 76 ++++++------
table/{ => internal}/partition_aggregate_test.go | 112 +++++++++---------
table/internal/partition_key.go | 57 +++++++++
table/internal/partition_record.go | 44 +++++++
table/{ => internal}/partition_struct_builder.go | 24 ++--
.../partition_struct_builder_test.go | 26 +++--
table/internal/position_delete_columns.go | 80 +++++++++++++
table/internal/record_batch_size.go | 22 ++++
table/{ => internal}/unified_partition_type.go | 19 ++-
.../{ => internal}/unified_partition_type_test.go | 39 ++-----
table/partition_statistics_v2_v3_test.go | 39 ++++---
table/partition_statistics_write.go | 117 ++++++++++---------
table/partition_statistics_write_test.go | 105 ++++++++---------
table/partitioned_fanout_writer.go | 50 ++------
table/pos_delete_partitioned_fanout_writer.go | 3 +-
table/scanner.go | 25 +---
table/snapshots_bench_test.go | 7 +-
table/snapshots_internal_test.go | 9 +-
table/transaction_delete.go | 2 +-
35 files changed, 665 insertions(+), 578 deletions(-)
diff --git a/table/arrow_scanner.go b/table/arrow_scanner.go
index d0f2c4198..61f7d835c 100644
--- a/table/arrow_scanner.go
+++ b/table/arrow_scanner.go
@@ -619,41 +619,12 @@ func filePathValueType(dt arrow.DataType) arrow.DataType {
return dt
}
-func filePathValues(values arrow.Array) (arrow.TypedArray[string], error) {
- switch arr := values.(type) {
- case *array.Dictionary:
- wrapped, err := array.NewDictWrapper[string](arr)
- if err != nil {
- return nil, fmt.Errorf("%w: file_path column is not
string: %w",
- iceberg.ErrInvalidSchema, err)
- }
-
- return wrapped, nil
- case arrow.TypedArray[string]:
- return arr, nil
- default:
- return nil, fmt.Errorf("%w: unsupported file_path column type
%s in position delete file",
- iceberg.ErrInvalidSchema, values.DataType())
- }
-}
-
type posDeleteCursor struct {
chunks []*array.Int64
chunkIndex int
offset int
}
-func validatePositionDeletePositions(positions *array.Int64) error {
- for row := range positions.Len() {
- if position := positions.Value(row); position < 0 {
- return fmt.Errorf("%w: negative pos %d in position
delete file",
- iceberg.ErrInvalidSchema, position)
- }
- }
-
- return nil
-}
-
func newPosDeleteCursor(posCol *arrow.Chunked) (posDeleteCursor, error) {
chunks := posCol.Chunks()
arrays := make([]*array.Int64, len(chunks))
@@ -764,7 +735,7 @@ func (a *posDeleteAccumulator) appendFilePathChunk(ctx
context.Context, filePath
return err
}
- paths, err := filePathValues(filePathChunk)
+ paths, err := tblutils.FilePathValues(filePathChunk)
if err != nil {
return err
}
@@ -1291,7 +1262,7 @@ func positionDeletePruningEnabled(schema *arrow.Schema)
(bool, error) {
}
func positionDeleteProjectionIndices(schema *arrow.Schema, reader
tblutils.FileReader) ([]int, error) {
- filePathIndex, posIndex, err := positionDeleteColumnIndices(schema)
+ filePathIndex, posIndex, err :=
tblutils.PositionDeleteColumnIndices(schema)
if err != nil {
return nil, err
}
@@ -1314,31 +1285,6 @@ func positionDeleteProjectionIndices(schema
*arrow.Schema, reader tblutils.FileR
return columns, nil
}
-func positionDeleteColumnIndices(schema *arrow.Schema) (int, int, error) {
- // Position-delete columns are resolved by their spec-defined names
because
- // Arrow schemas read from external files do not always retain Iceberg
IDs.
- requiredColumn := func(name string) (int, error) {
- indices := schema.FieldIndices(name)
- if len(indices) != 1 {
- return 0, fmt.Errorf("%w: position delete file must
contain exactly one %q column, found %d",
- iceberg.ErrInvalidSchema, name, len(indices))
- }
-
- return indices[0], nil
- }
-
- filePathIndex, err := requiredColumn("file_path")
- if err != nil {
- return 0, 0, err
- }
- posIndex, err := requiredColumn("pos")
- if err != nil {
- return 0, 0, err
- }
-
- return filePathIndex, posIndex, nil
-}
-
type set[T comparable] map[T]struct{}
// combinePositionalDeletes builds the surviving-row index list for a single
record
diff --git a/table/arrow_scanner_posdelete_bench_test.go
b/table/arrow_scanner_posdelete_bench_test.go
index 15d7a8d73..5b6921ccd 100644
--- a/table/arrow_scanner_posdelete_bench_test.go
+++ b/table/arrow_scanner_posdelete_bench_test.go
@@ -262,7 +262,7 @@ func readDeletesBefore(ctx context.Context, fs iceio.IO,
dataFile iceberg.DataFi
}
defer tbl.Release()
- filePathIndex, posIndex, err :=
positionDeleteColumnIndices(tbl.Schema())
+ filePathIndex, posIndex, err :=
tblutils.PositionDeleteColumnIndices(tbl.Schema())
if err != nil {
return nil, err
}
@@ -372,7 +372,7 @@ func groupPosDeletesByFilePathBefore(ctx context.Context,
filePathCol, posCol *a
unique.Release()
defer uniquePaths.Release()
- paths, err := filePathValues(uniquePaths)
+ paths, err := tblutils.FilePathValues(uniquePaths)
if err != nil {
return nil, err
}
diff --git a/table/arrow_scanner_posdelete_regression_test.go
b/table/arrow_scanner_posdelete_regression_test.go
index 9295416a2..ad3bd8ca9 100644
--- a/table/arrow_scanner_posdelete_regression_test.go
+++ b/table/arrow_scanner_posdelete_regression_test.go
@@ -60,7 +60,7 @@ func TestPositionDeleteColumnIndices(t *testing.T) {
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
- filePathIndex, posIndex, err :=
positionDeleteColumnIndices(arrow.NewSchema(test.fields, nil))
+ filePathIndex, posIndex, err :=
internal.PositionDeleteColumnIndices(arrow.NewSchema(test.fields, nil))
if test.wantErr != "" {
require.ErrorIs(t, err,
iceberg.ErrInvalidSchema)
require.ErrorContains(t, err, test.wantErr)
diff --git a/table/arrow_utils.go b/table/arrow_utils.go
index efabff084..fa6152ae3 100644
--- a/table/arrow_utils.go
+++ b/table/arrow_utils.go
@@ -60,10 +60,6 @@ const (
ArrowParquetFieldIDKey = "PARQUET:field_id"
defaultBinPackLookback = 20
-
- // recordBatchSize is the number of rows per Arrow record batch
produced by
- // metadata tables and partition statistics.
- recordBatchSize = 4096
)
// ArrowSchemaVisitor is an interface that can be implemented and used to
diff --git a/table/clustered_writer.go b/table/clustered_writer.go
index 90afdefb7..1e52dfcf4 100644
--- a/table/clustered_writer.go
+++ b/table/clustered_writer.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
// clusteredPartitionedWrite writes records to partitioned data files,
@@ -223,7 +224,7 @@ type closedPartitionSet map[any]closedPartitionSet
func (s closedPartitionSet) add(rec partitionRecord) {
node := s
for _, part := range rec {
- key := comparablePartitionKey(part)
+ key := tblutils.ComparablePartitionKey(part)
next, ok := node[key]
if !ok {
next = make(closedPartitionSet)
@@ -236,7 +237,7 @@ func (s closedPartitionSet) add(rec partitionRecord) {
func (s closedPartitionSet) contains(rec partitionRecord) bool {
node := s
for _, part := range rec {
- next, ok := node[comparablePartitionKey(part)]
+ next, ok := node[tblutils.ComparablePartitionKey(part)]
if !ok {
return false
}
diff --git a/table/equality_delete_index.go b/table/equality_delete_index.go
index afe63855f..ba7db20ce 100644
--- a/table/equality_delete_index.go
+++ b/table/equality_delete_index.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/iceberg-go"
iceberginternal "github.com/apache/iceberg-go/internal"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
)
@@ -345,7 +346,7 @@ func comparableEqualityDeletePartitionValue(value any)
(any, error) {
case float32, float64:
// Keep equality-delete indexing aligned with writer partition
keys:
// canonicalize NaNs within each width and preserve signed zero.
- return comparablePartitionKey(value), nil
+ return tblutils.ComparablePartitionKey(value), nil
case string:
return equalityDeleteStringPartitionValue(value), nil
case []byte:
diff --git a/table/inspect_all_manifests.go b/table/inspect_all_manifests.go
index 5e1b28c9e..917d795c2 100644
--- a/table/inspect_all_manifests.go
+++ b/table/inspect_all_manifests.go
@@ -25,6 +25,7 @@ import (
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
// AllManifests returns every manifest referenced by every snapshot currently
@@ -53,7 +54,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
rows := 0
emitted := false
- chunk := make([]iceberg.ManifestFile, 0, recordBatchSize)
+ chunk := make([]iceberg.ManifestFile, 0,
tblutils.RecordBatchSize)
emit := func() bool {
if rows == 0 {
return true
@@ -90,7 +91,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
}
// Gather manifests into a reused chunk so each record
batch is
- // filled to recordBatchSize across snapshot boundaries.
+ // filled to RecordBatchSize across snapshot boundaries.
referenceSnapshotID := snapshot.SnapshotID
appendChunk := func() bool {
if err := i.appendManifestRows(ctx, bldr,
slices.Values(chunk), &referenceSnapshotID); err != nil {
@@ -105,7 +106,7 @@ func (i InspectTable) AllManifests(ctx context.Context)
(array.RecordReader, err
}
for manifest := range manifests {
chunk = append(chunk, manifest)
- if rows+len(chunk) < recordBatchSize {
+ if rows+len(chunk) < tblutils.RecordBatchSize {
continue
}
if !appendChunk() || !emit() {
diff --git a/table/inspect_content_file_builder.go
b/table/inspect_content_file_builder.go
index c07b23e6a..fd294021f 100644
--- a/table/inspect_content_file_builder.go
+++ b/table/inspect_content_file_builder.go
@@ -25,6 +25,8 @@ import (
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/iceberg-go"
+ iceinternal "github.com/apache/iceberg-go/internal"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
func appendContentFileRecord(bldr *array.RecordBuilder, partitionType
*iceberg.StructType, file iceberg.DataFile) error {
@@ -59,7 +61,7 @@ type inspectContentFileBuilder struct {
filePath *array.StringBuilder
fileFormat *array.StringBuilder
specID *array.Int32Builder
- partition *partitionStructBuilder
+ partition *tblutils.PartitionStructBuilder
recordCount *array.Int64Builder
fileSize *array.Int64Builder
columnSizes *array.MapBuilder
@@ -105,11 +107,11 @@ func newInspectContentFileBuilderFromFields(
builder func(int) array.Builder,
partitionType *iceberg.StructType,
) (inspectContentFileBuilder, error) {
- lookup, err := newBuilderLookup("content-file", fields, builder)
+ lookup, err := tblutils.NewBuilderLookup("content-file", fields,
builder)
if err != nil {
return inspectContentFileBuilder{}, err
}
- if err := validateBuilderLookup("content-file", lookup,
inspectContentFileFieldIDs(partitionType)); err != nil {
+ if err := tblutils.ValidateBuilderLookup("content-file", lookup,
inspectContentFileFieldIDs(partitionType)); err != nil {
return inspectContentFileBuilder{}, err
}
@@ -131,7 +133,7 @@ func newInspectContentFileBuilderFromFields(
if bindErr != nil {
return out, bindErr
}
- if out.partition, err =
newPartitionStructBuilder(partitionBuilder, partitionType); err != nil {
+ if out.partition, err =
tblutils.NewPartitionStructBuilder(partitionBuilder, partitionType); err != nil
{
return out, err
}
}
@@ -194,18 +196,18 @@ func (b *inspectContentFileBuilder) append(file
iceberg.DataFile) error {
b.specID.Append(file.SpecID())
if b.partition != nil {
- if err := b.partition.append(dataFilePartition(file)); err !=
nil {
+ if err :=
b.partition.Append(iceinternal.BorrowedDataFilePartition(file)); err != nil {
return err
}
}
b.recordCount.Append(file.Count())
b.fileSize.Append(file.FileSizeBytes())
- columnSizes, keyMetadata, splitOffsets, equalityFieldIDs :=
dataFileCollections(file)
+ columnSizes, keyMetadata, splitOffsets, equalityFieldIDs :=
iceinternal.BorrowedDataFileCollections(file)
if err := appendInspectInt64Map(b.columnSizes, columnSizes,
&b.columnSizeFieldIDs); err != nil {
return err
}
- valueCounts, nullCounts, nanCounts, lowerBounds, upperBounds :=
dataFileStats(file)
+ valueCounts, nullCounts, nanCounts, lowerBounds, upperBounds :=
iceinternal.BorrowedDataFileStats(file)
if err := appendInspectInt64Map(b.valueCounts, valueCounts,
&b.valueCountFieldIDs); err != nil {
return err
}
diff --git a/table/inspect_entries.go b/table/inspect_entries.go
index 7cb166fbb..558001ba6 100644
--- a/table/inspect_entries.go
+++ b/table/inspect_entries.go
@@ -23,6 +23,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
// Entries returns every manifest entry in the current snapshot, including
@@ -38,7 +39,7 @@ func (i InspectTable) inspectEntries(
allSnapshots bool,
schemaFn func(*iceberg.StructType) *iceberg.Schema,
) (array.RecordReader, error) {
- partitionType, err := unifiedPartitionType(i.tbl.Metadata())
+ partitionType, err :=
tblutils.UnifiedPartitionType(i.tbl.Metadata().PartitionSpecs(), i.tbl.Schema())
if err != nil {
return nil, fmt.Errorf("inspect %s: %w", name, err)
}
diff --git a/table/inspect_files.go b/table/inspect_files.go
index a1aff8be3..3afcf140f 100644
--- a/table/inspect_files.go
+++ b/table/inspect_files.go
@@ -27,6 +27,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
// DataFiles returns the live data files in the current snapshot. Deleted
@@ -78,7 +79,7 @@ func (i InspectTable) inspectFiles(
allSnapshots bool,
includeManifest func(iceberg.ManifestFile) bool,
) (array.RecordReader, error) {
- partitionType, err := unifiedPartitionType(i.tbl.Metadata())
+ partitionType, err :=
tblutils.UnifiedPartitionType(i.tbl.Metadata().PartitionSpecs(), i.tbl.Schema())
if err != nil {
return nil, fmt.Errorf("inspect %s: %w", name, err)
}
@@ -233,7 +234,7 @@ func (i InspectTable) manifestEntryReaderFromManifestSource(
return
}
rows++
- if rows == recordBatchSize && !emit() {
+ if rows == tblutils.RecordBatchSize && !emit() {
return
}
}
diff --git a/table/inspect_internal_test.go b/table/inspect_internal_test.go
index 7b1966cfe..efdd5c048 100644
--- a/table/inspect_internal_test.go
+++ b/table/inspect_internal_test.go
@@ -40,6 +40,7 @@ import (
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/table/dv"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
@@ -1244,7 +1245,7 @@ func TestInspectAllManifestsPreservesSnapshotReferences(t
*testing.T) {
}
func TestInspectAllManifestsStreamsRecordBatches(t *testing.T) {
- const manifestCount = recordBatchSize + 1
+ const manifestCount = tblutils.RecordBatchSize + 1
manifests := make([]iceberg.ManifestFile, manifestCount)
for idx := range manifests {
@@ -1266,7 +1267,7 @@ func TestInspectAllManifestsStreamsRecordBatches(t
*testing.T) {
batchSizes = append(batchSizes, rr.RecordBatch().NumRows())
}
require.NoError(t, rr.Err())
- require.Equal(t, []int64{recordBatchSize, 1}, batchSizes)
+ require.Equal(t, []int64{tblutils.RecordBatchSize, 1}, batchSizes)
}
func TestInspectAllManifestsAllocator(t *testing.T) {
@@ -1276,7 +1277,7 @@ func TestInspectAllManifestsAllocator(t *testing.T) {
next bool
}{
{name: "before first batch", manifestCount: 1},
- {name: "after first batch", manifestCount: recordBatchSize + 1,
next: true},
+ {name: "after first batch", manifestCount:
tblutils.RecordBatchSize + 1, next: true},
} {
t.Run(tt.name, func(t *testing.T) {
checked :=
memory.NewCheckedAllocator(memory.DefaultAllocator)
@@ -1871,7 +1872,7 @@ func TestInspectAllEntriesIncludesDeleteManifests(t
*testing.T) {
func TestInspectAllEntriesStreamsBatches(t *testing.T) {
spec := *iceberg.UnpartitionedSpec
tbl := inspectDataFilesTable(t, spec,
- inspectDataFileEntries(t, spec, recordBatchSize+1))
+ inspectDataFileEntries(t, spec, tblutils.RecordBatchSize+1))
rr, err := tbl.Inspect().AllEntries(context.Background())
require.NoError(t, err)
@@ -1882,7 +1883,7 @@ func TestInspectAllEntriesStreamsBatches(t *testing.T) {
batchRows = append(batchRows, int(rr.RecordBatch().NumRows()))
}
require.NoError(t, rr.Err())
- require.Equal(t, []int{recordBatchSize, 1}, batchRows)
+ require.Equal(t, []int{tblutils.RecordBatchSize, 1}, batchRows)
}
func TestInspectAllEntriesEmptyTableEarlyRelease(t *testing.T) {
@@ -2335,8 +2336,8 @@ func TestInspectDataFilesStreamsBatchesAndSkipsDeleted(t
*testing.T) {
txn, memIO := createTestTransactionWithMemIO(t, spec)
schema := simpleSchema()
- entries := make([]iceberg.ManifestEntry, 0, recordBatchSize+2)
- for index := range recordBatchSize + 1 {
+ entries := make([]iceberg.ManifestEntry, 0, tblutils.RecordBatchSize+2)
+ for index := range tblutils.RecordBatchSize + 1 {
file := newTestDataFile(t, spec,
"mem://default/table-location/data/live-"+strconv.Itoa(index)+".parquet", nil)
sequenceNumber := int64(1)
@@ -2389,8 +2390,8 @@ func TestInspectDataFilesStreamsBatchesAndSkipsDeleted(t
*testing.T) {
}
}
require.NoError(t, rr.Err())
- require.Equal(t, []int{recordBatchSize, 1}, batchRows)
- require.Len(t, paths, recordBatchSize+1)
+ require.Equal(t, []int{tblutils.RecordBatchSize, 1}, batchRows)
+ require.Len(t, paths, tblutils.RecordBatchSize+1)
require.NotContains(t, paths, deletedPath)
}
@@ -2464,7 +2465,7 @@ func TestInspectDataFilesAllocator(t *testing.T) {
t.Cleanup(func() { checked.AssertSize(t, 0) })
spec := *iceberg.UnpartitionedSpec
- tbl := inspectDataFilesTable(t, spec,
inspectDataFileEntries(t, spec, recordBatchSize+1))
+ tbl := inspectDataFilesTable(t, spec,
inspectDataFileEntries(t, spec, tblutils.RecordBatchSize+1))
rr, err :=
tbl.Inspect(WithInspectAllocator(checked)).DataFiles(context.Background())
require.NoError(t, err)
@@ -3031,7 +3032,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
dataPath := "mem://position-deletes/table/data/data.parquet"
var deleteRows bytes.Buffer
deleteRows.WriteByte('[')
- for pos := range recordBatchSize {
+ for pos := range tblutils.RecordBatchSize {
if pos > 0 {
deleteRows.WriteByte(',')
}
@@ -3047,7 +3048,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
*iceberg.UnpartitionedSpec, tableSchema, snapshotID,
iceberg.ManifestContentDeletes,
[]iceberg.ManifestEntry{iceberg.NewManifestEntry(
iceberg.EntryStatusADDED, &snapshotID, &sequenceNumber,
&sequenceNumber,
- newPosDeleteFile(t, deletePath, recordBatchSize, 128),
+ newPosDeleteFile(t, deletePath,
tblutils.RecordBatchSize, 128),
)},
)
missingManifest := iceberg.NewManifestBuilder(
@@ -3062,7 +3063,7 @@ func TestInspectPositionDeletesDefersLaterManifestReads(t
*testing.T) {
require.NoError(t, err)
defer rr.Release()
require.True(t, rr.Next(), "reader error: %v", rr.Err())
- require.EqualValues(t, recordBatchSize, rr.RecordBatch().NumRows())
+ require.EqualValues(t, tblutils.RecordBatchSize,
rr.RecordBatch().NumRows())
}
func TestAppendParquetPositionDeleteRowsRejectsNullRow(t *testing.T) {
diff --git a/table/inspect_partitions.go b/table/inspect_partitions.go
index 32e9302bd..fc6825f0e 100644
--- a/table/inspect_partitions.go
+++ b/table/inspect_partitions.go
@@ -28,7 +28,9 @@ import (
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/scalar"
"github.com/apache/iceberg-go"
+ iceinternal "github.com/apache/iceberg-go/internal"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"golang.org/x/sync/errgroup"
)
@@ -36,7 +38,7 @@ import (
// files from the current snapshot. Files from evolved specs are coerced into
// the table-wide partition type before grouping.
func (i InspectTable) Partitions(ctx context.Context) (array.RecordReader,
error) {
- partitionType, err := unifiedPartitionType(i.tbl.Metadata())
+ partitionType, err :=
tblutils.UnifiedPartitionType(i.tbl.Metadata().PartitionSpecs(), i.tbl.Schema())
if err != nil {
return nil, fmt.Errorf("inspect partitions: %w", err)
}
@@ -54,14 +56,14 @@ func (i InspectTable) Partitions(ctx context.Context)
(array.RecordReader, error
return i.partitionAggregateReader(ctx, arrowSchema, partitionType,
aggregates), nil
}
-// partitionAggregateReader encodes at most recordBatchSize partitions per
+// partitionAggregateReader encodes at most RecordBatchSize partitions per
// Arrow batch. Aggregate discovery is eager, but the Arrow buffers are bounded
// and released as each record is consumed.
func (i InspectTable) partitionAggregateReader(
ctx context.Context,
arrowSchema *arrow.Schema,
partitionType *iceberg.StructType,
- aggregates []*partitionAggregate,
+ aggregates []*tblutils.PartitionAggregate,
) array.RecordReader {
return array.ReaderFromIter(arrowSchema, func(yield
func(arrow.RecordBatch, error) bool) {
bldr := array.NewRecordBuilder(i.alloc, arrowSchema)
@@ -80,7 +82,7 @@ func (i InspectTable) partitionAggregateReader(
return
}
- if (index+1)%recordBatchSize == 0 {
+ if (index+1)%tblutils.RecordBatchSize == 0 {
if !yield(bldr.NewRecordBatch(), nil) {
return
}
@@ -89,7 +91,7 @@ func (i InspectTable) partitionAggregateReader(
// Match the prior single-batch API for empty tables, but do
not emit
// an extra empty batch after an exact multiple of the batch
size.
- if len(aggregates) == 0 || len(aggregates)%recordBatchSize != 0
{
+ if len(aggregates) == 0 ||
len(aggregates)%tblutils.RecordBatchSize != 0 {
_ = yield(bldr.NewRecordBatch(), nil)
}
})
@@ -99,7 +101,7 @@ func (i InspectTable) partitionAggregateReader(
// per-manifest partition aggregation state.
const inspectPartitionManifestConcurrency = 8
-func (i InspectTable) partitionAggregates(ctx context.Context, partitionType
*iceberg.StructType) ([]*partitionAggregate, error) {
+func (i InspectTable) partitionAggregates(ctx context.Context, partitionType
*iceberg.StructType) ([]*tblutils.PartitionAggregate, error) {
snapshot := i.tbl.Metadata().CurrentSnapshot()
if snapshot == nil {
return nil, nil
@@ -120,8 +122,8 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
snapshotTimes[snapshot.SnapshotID] = snapshot.TimestampMs
}
- aggregates := make([]*partitionAggregate, 0)
- aggregateTree := newPartitionAggregateTree()
+ aggregates := make([]*tblutils.PartitionAggregate, 0)
+ aggregateTree := tblutils.NewPartitionAggregateTree()
// Buffer only a bounded number of manifests. Workers group their
entries
// independently, then their results are merged in manifest order.
@@ -132,11 +134,11 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
snapshotTimes, aggregateTree, &aggregates)
}
- partial := make([][]*partitionAggregate, len(batch))
+ partial := make([][]*tblutils.PartitionAggregate, len(batch))
g, gctx := errgroup.WithContext(ctx)
for index, manifest := range batch {
g.Go(func() error {
- localTree := newPartitionAggregateTree()
+ localTree :=
tblutils.NewPartitionAggregateTree()
return i.foldInspectPartitionManifest(gctx, fs,
manifest, partitionType,
snapshotTimes, localTree,
&partial[index])
@@ -157,10 +159,10 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
}
}
merged++
- aggregate :=
aggregateTree.lookupPartition(local.partition, partitionType)
+ aggregate :=
aggregateTree.LookupPartition(local.Partition, partitionType)
if aggregate == nil {
aggregates = append(aggregates, local)
-
aggregateTree.insert(newPartitionRecord(local.partition, partitionType), local)
+
aggregateTree.Insert(tblutils.NewPartitionRecord(local.Partition,
partitionType), local)
continue
}
@@ -192,7 +194,7 @@ func (i InspectTable) partitionAggregates(ctx
context.Context, partitionType *ic
}
sort.Slice(aggregates, func(left, right int) bool {
- return aggregates[left].orderingKey <
aggregates[right].orderingKey
+ return aggregates[left].OrderingKey <
aggregates[right].OrderingKey
})
return aggregates, nil
@@ -206,8 +208,8 @@ func (i InspectTable) foldInspectPartitionManifest(
manifest iceberg.ManifestFile,
partitionType *iceberg.StructType,
snapshotTimes map[int64]int64,
- aggregateTree *partitionAggregateTree,
- aggregates *[]*partitionAggregate,
+ aggregateTree *tblutils.PartitionAggregateTree,
+ aggregates *[]*tblutils.PartitionAggregate,
) error {
// Avoid opening remote manifest files after the caller has canceled.
if err := ctx.Err(); err != nil {
@@ -227,30 +229,30 @@ func (i InspectTable) foldInspectPartitionManifest(
entryIndex++
file := entry.DataFile()
- partitionValues := dataFilePartition(file)
- aggregate := aggregateTree.lookupPartition(partitionValues,
partitionType)
+ partitionValues := iceinternal.BorrowedDataFilePartition(file)
+ aggregate := aggregateTree.LookupPartition(partitionValues,
partitionType)
if aggregate == nil {
- partition := coercePartition(partitionValues,
partitionType)
- record := newPartitionRecord(partition, partitionType)
- aggregate = &partitionAggregate{
- partition: clonePartition(partition),
- orderingKey: inspectPartitionKey(partition),
+ partition := tblutils.CoercePartition(partitionValues,
partitionType)
+ record := tblutils.NewPartitionRecord(partition,
partitionType)
+ aggregate = &tblutils.PartitionAggregate{
+ Partition: tblutils.ClonePartition(partition),
+ OrderingKey: inspectPartitionKey(partition),
}
*aggregates = append(*aggregates, aggregate)
- aggregateTree.insert(record, aggregate)
+ aggregateTree.Insert(record, aggregate)
}
switch file.ContentType() {
case iceberg.EntryContentData:
- aggregate.dataRecordCount += file.Count()
- aggregate.dataFileCount++
- aggregate.dataFileSize += file.FileSizeBytes()
+ aggregate.DataRecordCount += file.Count()
+ aggregate.DataFileCount++
+ aggregate.DataFileSize += file.FileSizeBytes()
case iceberg.EntryContentPosDeletes:
- aggregate.positionDeleteCount += file.Count()
- aggregate.positionDeleteFiles++
+ aggregate.PositionDeleteCount += file.Count()
+ aggregate.PositionDeleteFiles++
case iceberg.EntryContentEqDeletes:
- aggregate.equalityDeleteCount += file.Count()
- aggregate.equalityDeleteFiles++
+ aggregate.EqualityDeleteCount += file.Count()
+ aggregate.EqualityDeleteFiles++
}
if file.ContentType() == iceberg.EntryContentData ||
@@ -263,25 +265,25 @@ func (i InspectTable) foldInspectPartitionManifest(
return ctx.Err()
}
-func mergeInspectPartitionAggregate(dst, src *partitionAggregate) {
- dst.dataRecordCount += src.dataRecordCount
- dst.dataFileCount += src.dataFileCount
- dst.dataFileSize += src.dataFileSize
- dst.positionDeleteCount += src.positionDeleteCount
- dst.positionDeleteFiles += src.positionDeleteFiles
- dst.equalityDeleteCount += src.equalityDeleteCount
- dst.equalityDeleteFiles += src.equalityDeleteFiles
-
- if src.lastUpdatedAt != nil &&
- (dst.lastUpdatedAt == nil || *src.lastUpdatedAt >
*dst.lastUpdatedAt) {
- dst.lastUpdatedAt = src.lastUpdatedAt
- dst.lastUpdatedSnapshot = src.lastUpdatedSnapshot
- dst.specID = src.specID
+func mergeInspectPartitionAggregate(dst, src *tblutils.PartitionAggregate) {
+ dst.DataRecordCount += src.DataRecordCount
+ dst.DataFileCount += src.DataFileCount
+ dst.DataFileSize += src.DataFileSize
+ dst.PositionDeleteCount += src.PositionDeleteCount
+ dst.PositionDeleteFiles += src.PositionDeleteFiles
+ dst.EqualityDeleteCount += src.EqualityDeleteCount
+ dst.EqualityDeleteFiles += src.EqualityDeleteFiles
+
+ if src.LastUpdatedAt != nil &&
+ (dst.LastUpdatedAt == nil || *src.LastUpdatedAt >
*dst.LastUpdatedAt) {
+ dst.LastUpdatedAt = src.LastUpdatedAt
+ dst.LastUpdatedSnapshot = src.LastUpdatedSnapshot
+ dst.SpecID = src.SpecID
}
}
func (i InspectTable) updatePartitionTimestamp(
- aggregate *partitionAggregate,
+ aggregate *tblutils.PartitionAggregate,
snapshotTimes map[int64]int64,
snapshotID int64,
specID int32,
@@ -294,13 +296,13 @@ func (i InspectTable) updatePartitionTimestamp(
return
}
timestamp := timestampMs * 1000
- if aggregate.lastUpdatedAt != nil && timestamp <=
*aggregate.lastUpdatedAt {
+ if aggregate.LastUpdatedAt != nil && timestamp <=
*aggregate.LastUpdatedAt {
return
}
- aggregate.lastUpdatedAt = ×tamp
+ aggregate.LastUpdatedAt = ×tamp
id := snapshotID
- aggregate.lastUpdatedSnapshot = &id
- aggregate.specID = specID
+ aggregate.LastUpdatedSnapshot = &id
+ aggregate.SpecID = specID
}
func inspectPartitionKey(partition map[int]any) string {
@@ -388,7 +390,7 @@ func PartitionsSchema(partitionType *iceberg.StructType)
*iceberg.Schema {
)
}
-func appendPartitionAggregate(bldr *array.RecordBuilder, partitionType
*iceberg.StructType, aggregate partitionAggregate) error {
+func appendPartitionAggregate(bldr *array.RecordBuilder, partitionType
*iceberg.StructType, aggregate tblutils.PartitionAggregate) error {
idx := 0
if partitionType != nil && partitionType.NumFields() > 0 {
partition := bldr.Field(idx).(*array.StructBuilder)
@@ -396,13 +398,13 @@ func appendPartitionAggregate(bldr *array.RecordBuilder,
partitionType *iceberg.
partition.Append(true)
for fieldIndex := range partitionType.NumFields() {
field := partitionType.Field(fieldIndex)
- value := aggregate.partition[field.ID]
+ value := aggregate.Partition[field.ID]
if value == nil {
partition.FieldBuilder(fieldIndex).AppendNull()
continue
}
- valueScalar, err := partitionValueScalar(value,
field.Type, arrowType.Field(fieldIndex).Type)
+ valueScalar, err :=
tblutils.PartitionValueScalar(value, field.Type,
arrowType.Field(fieldIndex).Type)
if err != nil {
return fmt.Errorf("partition field %q: %w",
field.Name, err)
}
@@ -411,33 +413,33 @@ func appendPartitionAggregate(bldr *array.RecordBuilder,
partitionType *iceberg.
}
}
idx++
- bldr.Field(idx).(*array.Int32Builder).Append(aggregate.specID)
+ bldr.Field(idx).(*array.Int32Builder).Append(aggregate.SpecID)
idx++
}
- bldr.Field(idx).(*array.Int64Builder).Append(aggregate.dataRecordCount)
+ bldr.Field(idx).(*array.Int64Builder).Append(aggregate.DataRecordCount)
idx++
- bldr.Field(idx).(*array.Int32Builder).Append(aggregate.dataFileCount)
+ bldr.Field(idx).(*array.Int32Builder).Append(aggregate.DataFileCount)
idx++
- bldr.Field(idx).(*array.Int64Builder).Append(aggregate.dataFileSize)
+ bldr.Field(idx).(*array.Int64Builder).Append(aggregate.DataFileSize)
idx++
-
bldr.Field(idx).(*array.Int64Builder).Append(aggregate.positionDeleteCount)
+
bldr.Field(idx).(*array.Int64Builder).Append(aggregate.PositionDeleteCount)
idx++
-
bldr.Field(idx).(*array.Int32Builder).Append(aggregate.positionDeleteFiles)
+
bldr.Field(idx).(*array.Int32Builder).Append(aggregate.PositionDeleteFiles)
idx++
-
bldr.Field(idx).(*array.Int64Builder).Append(aggregate.equalityDeleteCount)
+
bldr.Field(idx).(*array.Int64Builder).Append(aggregate.EqualityDeleteCount)
idx++
-
bldr.Field(idx).(*array.Int32Builder).Append(aggregate.equalityDeleteFiles)
+
bldr.Field(idx).(*array.Int32Builder).Append(aggregate.EqualityDeleteFiles)
idx++
- if aggregate.lastUpdatedAt == nil {
+ if aggregate.LastUpdatedAt == nil {
bldr.Field(idx).(*array.TimestampBuilder).AppendNull()
} else {
-
bldr.Field(idx).(*array.TimestampBuilder).Append(arrow.Timestamp(*aggregate.lastUpdatedAt))
+
bldr.Field(idx).(*array.TimestampBuilder).Append(arrow.Timestamp(*aggregate.LastUpdatedAt))
}
idx++
- if aggregate.lastUpdatedSnapshot == nil {
+ if aggregate.LastUpdatedSnapshot == nil {
bldr.Field(idx).(*array.Int64Builder).AppendNull()
} else {
-
bldr.Field(idx).(*array.Int64Builder).Append(*aggregate.lastUpdatedSnapshot)
+
bldr.Field(idx).(*array.Int64Builder).Append(*aggregate.LastUpdatedSnapshot)
}
return nil
diff --git a/table/inspect_partitions_batch_test.go
b/table/inspect_partitions_batch_test.go
index 920956493..ee711b4ac 100644
--- a/table/inspect_partitions_batch_test.go
+++ b/table/inspect_partitions_batch_test.go
@@ -26,13 +26,14 @@ import (
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/stretchr/testify/require"
)
func inspectPartitionBatchFixture(
tb testing.TB,
count int,
-) (*iceberg.StructType, *arrow.Schema, []*partitionAggregate) {
+) (*iceberg.StructType, *arrow.Schema, []*tblutils.PartitionAggregate) {
tb.Helper()
partitionType := iceberg.NewStructType(
@@ -43,12 +44,12 @@ func inspectPartitionBatchFixture(
tb.Fatal(err)
}
- aggregates := make([]*partitionAggregate, count)
+ aggregates := make([]*tblutils.PartitionAggregate, count)
for i := range aggregates {
- aggregates[i] = &partitionAggregate{
- partition: map[int]any{1000: int32(i)},
- dataRecordCount: int64(i + 1),
- dataFileCount: 1,
+ aggregates[i] = &tblutils.PartitionAggregate{
+ Partition: map[int]any{1000: int32(i)},
+ DataRecordCount: int64(i + 1),
+ DataFileCount: 1,
}
}
@@ -57,8 +58,8 @@ func inspectPartitionBatchFixture(
func TestInspectPartitionAggregateReaderBoundedBatches(t *testing.T) {
for _, count := range []int{
- 0, 1, recordBatchSize - 1, recordBatchSize,
- recordBatchSize + 1, 2*recordBatchSize + 1,
+ 0, 1, tblutils.RecordBatchSize - 1, tblutils.RecordBatchSize,
+ tblutils.RecordBatchSize + 1, 2*tblutils.RecordBatchSize + 1,
} {
t.Run(fmt.Sprintf("partitions=%d", count), func(t *testing.T) {
partitionType, arrowSchema, aggregates :=
inspectPartitionBatchFixture(t, count)
@@ -74,7 +75,7 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
for reader.Next() {
batch := reader.RecordBatch()
batchSizes = append(batchSizes,
int(batch.NumRows()))
- require.LessOrEqual(t, batch.NumRows(),
int64(recordBatchSize))
+ require.LessOrEqual(t, batch.NumRows(),
int64(tblutils.RecordBatchSize))
partition :=
batch.Column(0).(*array.Struct).Field(0).(*array.Int32)
recordCount := batch.Column(2).(*array.Int64)
@@ -89,9 +90,9 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
if count == 0 {
require.Equal(t, []int{0}, batchSizes)
} else {
- want := make([]int, 0,
(count+recordBatchSize-1)/recordBatchSize)
- for remaining := count; remaining > 0;
remaining -= recordBatchSize {
- want = append(want, min(remaining,
recordBatchSize))
+ want := make([]int, 0,
(count+tblutils.RecordBatchSize-1)/tblutils.RecordBatchSize)
+ for remaining := count; remaining > 0;
remaining -= tblutils.RecordBatchSize {
+ want = append(want, min(remaining,
tblutils.RecordBatchSize))
}
require.Equal(t, want, batchSizes)
}
@@ -102,7 +103,7 @@ func TestInspectPartitionAggregateReaderBoundedBatches(t
*testing.T) {
// Exercise the public metadata-table reader across a real manifest, including
// the boundary between two Arrow batches.
func TestInspectPartitionsAcrossRecordBatchBoundary(t *testing.T) {
- const count = recordBatchSize + 1
+ const count = tblutils.RecordBatchSize + 1
spec := partitionedSpec()
const snapshotID = int64(1)
@@ -146,12 +147,12 @@ func TestInspectPartitionsAcrossRecordBatchBoundary(t
*testing.T) {
}
require.NoError(t, reader.Err())
require.Len(t, seen, count)
- require.Equal(t, []int{recordBatchSize, 1}, batchSizes)
+ require.Equal(t, []int{tblutils.RecordBatchSize, 1}, batchSizes)
}
func TestInspectPartitionAggregateReaderCancellation(t *testing.T) {
partitionType, arrowSchema, aggregates := inspectPartitionBatchFixture(
- t, 2*recordBatchSize)
+ t, 2*tblutils.RecordBatchSize)
ctx, cancel := context.WithCancel(t.Context())
defer cancel()
@@ -160,7 +161,7 @@ func TestInspectPartitionAggregateReaderCancellation(t
*testing.T) {
defer reader.Release()
require.True(t, reader.Next())
- require.EqualValues(t, recordBatchSize, reader.RecordBatch().NumRows())
+ require.EqualValues(t, tblutils.RecordBatchSize,
reader.RecordBatch().NumRows())
cancel()
require.False(t, reader.Next())
require.ErrorIs(t, reader.Err(), context.Canceled)
diff --git a/table/inspect_partitions_bench_test.go
b/table/inspect_partitions_bench_test.go
index 179415fe1..2f1c27a75 100644
--- a/table/inspect_partitions_bench_test.go
+++ b/table/inspect_partitions_bench_test.go
@@ -22,6 +22,7 @@ import (
"testing"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
type inspectPartitionAggregationBenchmarkCase struct {
@@ -63,38 +64,38 @@ func benchmarkInspectPartitionAggregation(
b.ReportAllocs()
b.ReportMetric(float64(len(files)), "files/op")
for b.Loop() {
- tree := newPartitionAggregateTree()
+ tree := tblutils.NewPartitionAggregateTree()
aggregateCount := 0
for _, file := range files {
- var aggregate *partitionAggregate
+ var aggregate *tblutils.PartitionAggregate
if materialize {
- partition := coercePartition(file.Partition(),
partitionType)
- record := newPartitionRecord(partition,
partitionType)
- aggregate = tree.lookup(record)
+ partition :=
tblutils.CoercePartition(file.Partition(), partitionType)
+ record :=
tblutils.NewPartitionRecord(partition, partitionType)
+ aggregate = tree.Lookup(record)
if aggregate == nil {
- aggregate = &partitionAggregate{
- partition:
clonePartition(partition),
- orderingKey:
inspectPartitionKey(partition),
+ aggregate =
&tblutils.PartitionAggregate{
+ Partition:
tblutils.ClonePartition(partition),
+ OrderingKey:
inspectPartitionKey(partition),
}
- tree.insert(record, aggregate)
+ tree.Insert(record, aggregate)
aggregateCount++
}
} else {
partitionValues := dataFilePartition(file)
- aggregate =
tree.lookupPartition(partitionValues, partitionType)
+ aggregate =
tree.LookupPartition(partitionValues, partitionType)
if aggregate == nil {
- partition :=
coercePartition(partitionValues, partitionType)
- record := newPartitionRecord(partition,
partitionType)
- aggregate = &partitionAggregate{
- partition:
clonePartition(partition),
- orderingKey:
inspectPartitionKey(partition),
+ partition :=
tblutils.CoercePartition(partitionValues, partitionType)
+ record :=
tblutils.NewPartitionRecord(partition, partitionType)
+ aggregate =
&tblutils.PartitionAggregate{
+ Partition:
tblutils.ClonePartition(partition),
+ OrderingKey:
inspectPartitionKey(partition),
}
- tree.insert(record, aggregate)
+ tree.Insert(record, aggregate)
aggregateCount++
}
}
- aggregate.dataFileCount++
+ aggregate.DataFileCount++
}
inspectPartitionAggregationBenchmarkSink = aggregateCount
}
@@ -166,7 +167,7 @@ func BenchmarkInspectPartitionBinaryLookup(b *testing.B) {
}
partitionType := iceberg.NewStructType(fields...)
- tree := newPartitionAggregateTree()
+ tree := tblutils.NewPartitionAggregateTree()
partitions := make([]map[int]any, partitionCount)
for i := range partitions {
record := make(partitionRecord, fieldCount)
@@ -176,7 +177,7 @@ func BenchmarkInspectPartitionBinaryLookup(b *testing.B) {
record[j] = value
partition[field.ID] = value
}
- tree.insert(record, &partitionAggregate{})
+ tree.Insert(record, &tblutils.PartitionAggregate{})
partitions[i] = partition
}
@@ -184,7 +185,7 @@ func BenchmarkInspectPartitionBinaryLookup(b *testing.B) {
b.ReportAllocs()
b.ResetTimer()
for b.Loop() {
- if tree.lookupPartition(partitions[index], partitionType) ==
nil {
+ if tree.LookupPartition(partitions[index], partitionType) ==
nil {
b.Fatal("partition not found")
}
index++
diff --git a/table/inspect_partitions_parallel_test.go
b/table/inspect_partitions_parallel_test.go
index 624e97c98..e092db15a 100644
--- a/table/inspect_partitions_parallel_test.go
+++ b/table/inspect_partitions_parallel_test.go
@@ -28,6 +28,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/stretchr/testify/require"
)
@@ -166,28 +167,28 @@ func TestMergeInspectPartitionAggregateTimestampTies(t
*testing.T) {
const timestamp = int64(123000)
firstSnapshot := int64(10)
secondSnapshot := int64(20)
- dst := &partitionAggregate{
- dataRecordCount: 3, dataFileCount: 1, specID: 1,
- lastUpdatedAt: new(timestamp), lastUpdatedSnapshot:
&firstSnapshot,
+ dst := &tblutils.PartitionAggregate{
+ DataRecordCount: 3, DataFileCount: 1, SpecID: 1,
+ LastUpdatedAt: new(timestamp), LastUpdatedSnapshot:
&firstSnapshot,
}
- sameTime := &partitionAggregate{
- dataRecordCount: 5, dataFileCount: 2, specID: 2,
- lastUpdatedAt: new(timestamp), lastUpdatedSnapshot:
&secondSnapshot,
+ sameTime := &tblutils.PartitionAggregate{
+ DataRecordCount: 5, DataFileCount: 2, SpecID: 2,
+ LastUpdatedAt: new(timestamp), LastUpdatedSnapshot:
&secondSnapshot,
}
mergeInspectPartitionAggregate(dst, sameTime)
// The earlier manifest wins a timestamp tie, but counts still add up.
- require.EqualValues(t, 8, dst.dataRecordCount)
- require.EqualValues(t, 3, dst.dataFileCount)
- require.EqualValues(t, 1, dst.specID)
- require.Equal(t, firstSnapshot, *dst.lastUpdatedSnapshot)
+ require.EqualValues(t, 8, dst.DataRecordCount)
+ require.EqualValues(t, 3, dst.DataFileCount)
+ require.EqualValues(t, 1, dst.SpecID)
+ require.Equal(t, firstSnapshot, *dst.LastUpdatedSnapshot)
newerTime := timestamp + 1
- newer := &partitionAggregate{
- specID: 3, lastUpdatedAt: &newerTime, lastUpdatedSnapshot:
&secondSnapshot,
+ newer := &tblutils.PartitionAggregate{
+ SpecID: 3, LastUpdatedAt: &newerTime, LastUpdatedSnapshot:
&secondSnapshot,
}
mergeInspectPartitionAggregate(dst, newer)
- require.EqualValues(t, 3, dst.specID)
- require.Equal(t, newerTime, *dst.lastUpdatedAt)
- require.Equal(t, secondSnapshot, *dst.lastUpdatedSnapshot)
+ require.EqualValues(t, 3, dst.SpecID)
+ require.Equal(t, newerTime, *dst.LastUpdatedAt)
+ require.Equal(t, secondSnapshot, *dst.LastUpdatedSnapshot)
}
diff --git a/table/inspect_position_deletes.go
b/table/inspect_position_deletes.go
index 817f79361..a5e258c10 100644
--- a/table/inspect_position_deletes.go
+++ b/table/inspect_position_deletes.go
@@ -104,7 +104,7 @@ type positionDeleteRecordAppender struct {
filePath *array.StringBuilder
pos *array.Int64Builder
row *array.StructBuilder
- partition *partitionStructBuilder
+ partition *tblutils.PartitionStructBuilder
specID *array.Int32Builder
deleteFilePath *array.StringBuilder
contentOffset *array.Int64Builder
@@ -182,7 +182,7 @@ func newPositionDeleteRecordAppender(
projection: projection,
}
if partitionType.NumFields() > 0 {
- partitionBuilder, err := newPartitionStructBuilder(
+ partitionBuilder, err := tblutils.NewPartitionStructBuilder(
bldr.Field(nextField).(*array.StructBuilder),
partitionType)
if err != nil {
return out, err
@@ -216,7 +216,7 @@ func (a positionDeleteRecordAppender) prepareFile(file
iceberg.DataFile) positio
deleteFilePath: file.FilePath(),
}
if a.partition != nil {
- borrowedPartition := dataFilePartition(file)
+ borrowedPartition := iceinternal.BorrowedDataFilePartition(file)
meta.partition = make(map[int]any, len(borrowedPartition))
for oldID, value := range borrowedPartition {
newID, ok := a.partitionIDByOld[oldID]
@@ -261,7 +261,7 @@ func (a positionDeleteRecordAppender) appendPrepared(
}
if a.partition != nil {
- if err := a.partition.append(meta.partition); err != nil {
+ if err := a.partition.Append(meta.partition); err != nil {
return err
}
}
@@ -537,7 +537,7 @@ func (i InspectTable) positionDeleteRecordReader(
return false, err
}
rows++
- if rows == recordBatchSize {
+ if rows == tblutils.RecordBatchSize {
return emit(), nil
}
@@ -701,11 +701,11 @@ func appendPositionDeleteRecord(
appendRow appendPositionDeleteRow,
projection positionDeleteProjectionOptions,
) (bool, error) {
- filePathIndex, posIndex, err :=
positionDeleteColumnIndices(record.Schema())
+ filePathIndex, posIndex, err :=
tblutils.PositionDeleteColumnIndices(record.Schema())
if err != nil {
return false, err
}
- filePaths, err := filePathValues(record.Column(filePathIndex))
+ filePaths, err := tblutils.FilePathValues(record.Column(filePathIndex))
if err != nil {
return false, err
}
@@ -720,7 +720,7 @@ func appendPositionDeleteRecord(
if positions.NullN() > 0 {
return false, fmt.Errorf("%w: null pos in position delete
file", iceberg.ErrInvalidSchema)
}
- if err := validatePositionDeletePositions(positions); err != nil {
+ if err := tblutils.ValidatePositionDeletePositions(positions); err !=
nil {
return false, err
}
@@ -804,7 +804,7 @@ func positionDeletesPartitionType(
metadata Metadata,
) (*iceberg.StructType, map[int]int, error) {
currentSchema := metadata.CurrentSchema()
- base, err := unifiedPartitionTypeWithSchema(metadata, currentSchema)
+ base, err := tblutils.UnifiedPartitionType(metadata.PartitionSpecs(),
currentSchema)
if err != nil {
return nil, nil, err
}
diff --git a/table/partition_aggregate.go
b/table/internal/partition_aggregate.go
similarity index 64%
rename from table/partition_aggregate.go
rename to table/internal/partition_aggregate.go
index fa7ffdfbd..c90698f28 100644
--- a/table/partition_aggregate.go
+++ b/table/internal/partition_aggregate.go
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal
import (
"slices"
@@ -23,57 +23,57 @@ import (
"github.com/apache/iceberg-go"
)
-type partitionAggregate struct {
- specID int32
- partition map[int]any
- dataRecordCount int64
- dataFileCount int32
- dataFileSize int64
- positionDeleteCount int64
- positionDeleteFiles int32
- equalityDeleteCount int64
- equalityDeleteFiles int32
- lastUpdatedAt *int64
- lastUpdatedSnapshot *int64
- orderingKey string
+type PartitionAggregate struct {
+ SpecID int32
+ Partition map[int]any
+ DataRecordCount int64
+ DataFileCount int32
+ DataFileSize int64
+ PositionDeleteCount int64
+ PositionDeleteFiles int32
+ EqualityDeleteCount int64
+ EqualityDeleteFiles int32
+ LastUpdatedAt *int64
+ LastUpdatedSnapshot *int64
+ OrderingKey string
// Persisted partition statistics distinguish DVs from classic delete
files
// and expose an exact live-row total only when metadata proves it.
- deletionVectorCount int32
- totalRecordCount *int64
+ DeletionVectorCount int32
+ TotalRecordCount *int64
// Partition statistics store timestamps in milliseconds, while the
inspect
// Arrow output above uses microseconds.
- statisticsUpdatedAt *int64
- statisticsUpdatedSnapshot *int64
+ StatisticsUpdatedAt *int64
+ StatisticsUpdatedSnapshot *int64
}
-type partitionAggregateTree struct {
- children map[any]*partitionAggregateTree
- binaryChildren map[string]*partitionAggregateTree
- aggregate *partitionAggregate
+type PartitionAggregateTree struct {
+ children map[any]*PartitionAggregateTree
+ binaryChildren map[string]*PartitionAggregateTree
+ aggregate *PartitionAggregate
}
-func newPartitionAggregateTree() *partitionAggregateTree {
- return &partitionAggregateTree{}
+func NewPartitionAggregateTree() *PartitionAggregateTree {
+ return &PartitionAggregateTree{}
}
// child uses a typed map for binary values to avoid interface-backed keys
// during repeated lookups. Other values retain their existing key types.
-func (t *partitionAggregateTree) child(value any) (*partitionAggregateTree,
bool) {
+func (t *PartitionAggregateTree) child(value any) (*PartitionAggregateTree,
bool) {
if binary, ok := value.([]byte); ok {
child, found := t.binaryChildren[string(binary)]
return child, found
}
- child, found := t.children[comparablePartitionKey(value)]
+ child, found := t.children[ComparablePartitionKey(value)]
return child, found
}
-func (t *partitionAggregateTree) setChild(value any, child
*partitionAggregateTree) {
+func (t *PartitionAggregateTree) setChild(value any, child
*PartitionAggregateTree) {
if binary, ok := value.([]byte); ok {
if t.binaryChildren == nil {
- t.binaryChildren =
make(map[string]*partitionAggregateTree)
+ t.binaryChildren =
make(map[string]*PartitionAggregateTree)
}
// A stored string key owns its bytes even if the input buffer
changes.
t.binaryChildren[string(binary)] = child
@@ -82,12 +82,12 @@ func (t *partitionAggregateTree) setChild(value any, child
*partitionAggregateTr
}
if t.children == nil {
- t.children = make(map[any]*partitionAggregateTree)
+ t.children = make(map[any]*PartitionAggregateTree)
}
- t.children[comparablePartitionKey(value)] = child
+ t.children[ComparablePartitionKey(value)] = child
}
-func (t *partitionAggregateTree) lookup(record partitionRecord)
*partitionAggregate {
+func (t *PartitionAggregateTree) Lookup(record PartitionRecord)
*PartitionAggregate {
node := t
for _, value := range record {
child, ok := node.child(value)
@@ -100,10 +100,10 @@ func (t *partitionAggregateTree) lookup(record
partitionRecord) *partitionAggreg
return node.aggregate
}
-func (t *partitionAggregateTree) lookupPartition(
+func (t *PartitionAggregateTree) LookupPartition(
partition map[int]any,
partitionType *iceberg.StructType,
-) *partitionAggregate {
+) *PartitionAggregate {
node := t
for i := range partitionType.NumFields() {
child, ok := node.child(partition[partitionType.Field(i).ID])
@@ -116,15 +116,15 @@ func (t *partitionAggregateTree) lookupPartition(
return node.aggregate
}
-// insert walks the positional record, while lookupPartition walks partition
+// Insert walks the positional record, while LookupPartition walks partition
// field IDs. Build records with the same partition type so their field order
// stays aligned.
-func (t *partitionAggregateTree) insert(record partitionRecord, aggregate
*partitionAggregate) {
+func (t *PartitionAggregateTree) Insert(record PartitionRecord, aggregate
*PartitionAggregate) {
node := t
for _, value := range record {
child, ok := node.child(value)
if !ok {
- child = newPartitionAggregateTree()
+ child = NewPartitionAggregateTree()
node.setChild(value, child)
}
node = child
@@ -132,7 +132,7 @@ func (t *partitionAggregateTree) insert(record
partitionRecord, aggregate *parti
node.aggregate = aggregate
}
-func coercePartition(values map[int]any, partitionType *iceberg.StructType)
map[int]any {
+func CoercePartition(values map[int]any, partitionType *iceberg.StructType)
map[int]any {
if partitionType == nil || partitionType.NumFields() == 0 {
return nil
}
@@ -148,7 +148,7 @@ func coercePartition(values map[int]any, partitionType
*iceberg.StructType) map[
return coerced
}
-func clonePartition(partition map[int]any) map[int]any {
+func ClonePartition(partition map[int]any) map[int]any {
if partition == nil {
return nil
}
diff --git a/table/partition_aggregate_test.go
b/table/internal/partition_aggregate_test.go
similarity index 57%
rename from table/partition_aggregate_test.go
rename to table/internal/partition_aggregate_test.go
index 968cb270b..8b1d8f060 100644
--- a/table/partition_aggregate_test.go
+++ b/table/internal/partition_aggregate_test.go
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal
import (
"math"
@@ -30,15 +30,15 @@ func TestPartitionAggregateTreeBinaryKeys(t *testing.T) {
iceberg.NestedField{ID: 1000, Name: "first", Type:
iceberg.PrimitiveTypes.Binary},
iceberg.NestedField{ID: 1001, Name: "second", Type:
iceberg.PrimitiveTypes.Binary},
)
- tree := newPartitionAggregateTree()
+ tree := NewPartitionAggregateTree()
- check := func(first, second any, want *partitionAggregate) {
+ check := func(first, second any, want *PartitionAggregate) {
t.Helper()
- if got := tree.lookup(partitionRecord{first, second}); got !=
want {
+ if got := tree.Lookup(PartitionRecord{first, second}); got !=
want {
t.Fatalf("positional lookup (%v, %v) = %p, want %p",
first, second, got, want)
}
partition := map[int]any{1000: first, 1001: second}
- if got := tree.lookupPartition(partition, partitionType); got
!= want {
+ if got := tree.LookupPartition(partition, partitionType); got
!= want {
t.Fatalf("map lookup (%v, %v) = %p, want %p", first,
second, got, want)
}
}
@@ -47,81 +47,81 @@ func TestPartitionAggregateTreeBinaryKeys(t *testing.T) {
first := []byte{0, 0xff}
second := []byte("x/y")
- original := &partitionAggregate{}
- tree.insert(partitionRecord{first, second}, original)
+ original := &PartitionAggregate{}
+ tree.Insert(PartitionRecord{first, second}, original)
first[0] = 1
second[0] = 'z'
check([]byte{0, 0xff}, []byte("x/y"), original)
check(first, second, nil)
- nullFirst := &partitionAggregate{}
- emptyFirst := &partitionAggregate{}
- tree.insert(partitionRecord{nil, []byte("x")}, nullFirst)
- tree.insert(partitionRecord{[]byte{}, []byte("x")}, emptyFirst)
+ nullFirst := &PartitionAggregate{}
+ emptyFirst := &PartitionAggregate{}
+ tree.Insert(PartitionRecord{nil, []byte("x")}, nullFirst)
+ tree.Insert(PartitionRecord{[]byte{}, []byte("x")}, emptyFirst)
check(nil, []byte("x"), nullFirst)
check([]byte{}, []byte("x"), emptyFirst)
check([]byte(nil), []byte("x"), emptyFirst)
- binaryFirst := &partitionAggregate{}
- stringFirst := &partitionAggregate{}
- tree.insert(partitionRecord{[]byte("same"), []byte("tail")},
binaryFirst)
- tree.insert(partitionRecord{"same", []byte("tail")}, stringFirst)
+ binaryFirst := &PartitionAggregate{}
+ stringFirst := &PartitionAggregate{}
+ tree.Insert(PartitionRecord{[]byte("same"), []byte("tail")},
binaryFirst)
+ tree.Insert(PartitionRecord{"same", []byte("tail")}, stringFirst)
check([]byte("same"), []byte("tail"), binaryFirst)
check("same", []byte("tail"), stringFirst)
- otherNested := &partitionAggregate{}
- tree.insert(partitionRecord{[]byte("same"), []byte("other")},
otherNested)
+ otherNested := &PartitionAggregate{}
+ tree.Insert(PartitionRecord{[]byte("same"), []byte("other")},
otherNested)
check([]byte("same"), []byte("other"), otherNested)
check([]byte("same"), []byte("tail"), binaryFirst)
}
func TestPartitionAggregateTreeMixedKeys(t *testing.T) {
- tree := newPartitionAggregateTree()
- negativeZero := &partitionAggregate{}
- positiveZero := &partitionAggregate{}
- nan := &partitionAggregate{}
+ tree := NewPartitionAggregateTree()
+ negativeZero := &PartitionAggregate{}
+ positiveZero := &PartitionAggregate{}
+ nan := &PartitionAggregate{}
- tree.insert(partitionRecord{[]byte("scope"), math.Copysign(0, -1)},
negativeZero)
- tree.insert(partitionRecord{[]byte("scope"), float64(0)}, positiveZero)
- tree.insert(partitionRecord{[]byte("scope"),
math.Float64frombits(0x7ff8000000000001)}, nan)
+ tree.Insert(PartitionRecord{[]byte("scope"), math.Copysign(0, -1)},
negativeZero)
+ tree.Insert(PartitionRecord{[]byte("scope"), float64(0)}, positiveZero)
+ tree.Insert(PartitionRecord{[]byte("scope"),
math.Float64frombits(0x7ff8000000000001)}, nan)
for _, test := range []struct {
value float64
- want *partitionAggregate
+ want *PartitionAggregate
}{
{math.Copysign(0, -1), negativeZero},
{0, positiveZero},
{math.Float64frombits(0x7ff8000000000002), nan},
} {
- if got := tree.lookup(partitionRecord{[]byte("scope"),
test.value}); got != test.want {
+ if got := tree.Lookup(PartitionRecord{[]byte("scope"),
test.value}); got != test.want {
t.Fatalf("lookup (%v) = %p, want %p", test.value, got,
test.want)
}
}
}
func TestPartitionAggregateTreeHandlesBinaryAndNaNValues(t *testing.T) {
- tree := newPartitionAggregateTree()
- aggregate := &partitionAggregate{specID: 1}
- record := partitionRecord{[]byte{1, 2, 3}, math.NaN()}
- tree.insert(record, aggregate)
+ tree := NewPartitionAggregateTree()
+ aggregate := &PartitionAggregate{SpecID: 1}
+ record := PartitionRecord{[]byte{1, 2, 3}, math.NaN()}
+ tree.Insert(record, aggregate)
- require.Same(t, aggregate, tree.lookup(partitionRecord{[]byte{1, 2, 3},
math.NaN()}))
- require.Nil(t, tree.lookup(partitionRecord{[]byte{1, 2, 4},
math.NaN()}))
+ require.Same(t, aggregate, tree.Lookup(PartitionRecord{[]byte{1, 2, 3},
math.NaN()}))
+ require.Nil(t, tree.Lookup(PartitionRecord{[]byte{1, 2, 4},
math.NaN()}))
}
func TestPartitionAggregateTreeDistinguishesFloatWidthsAndSignedZero(t
*testing.T) {
- tree := newPartitionAggregateTree()
- float32Aggregate := &partitionAggregate{specID: 1}
- float32Record := partitionRecord{math.Float32frombits(0xffc00001)}
- tree.insert(float32Record, float32Aggregate)
-
- require.Same(t, float32Aggregate,
tree.lookup(partitionRecord{math.Float32frombits(0x7fc00002)}))
- require.Nil(t,
tree.lookup(partitionRecord{math.Float64frombits(0x7ff8000000000001)}))
-
- negativeZeroAggregate := &partitionAggregate{specID: 2}
- tree.insert(partitionRecord{math.Copysign(0, -1)},
negativeZeroAggregate)
- require.Same(t, negativeZeroAggregate,
tree.lookup(partitionRecord{math.Copysign(0, -1)}))
- require.Nil(t, tree.lookup(partitionRecord{float64(0)}))
+ tree := NewPartitionAggregateTree()
+ float32Aggregate := &PartitionAggregate{SpecID: 1}
+ float32Record := PartitionRecord{math.Float32frombits(0xffc00001)}
+ tree.Insert(float32Record, float32Aggregate)
+
+ require.Same(t, float32Aggregate,
tree.Lookup(PartitionRecord{math.Float32frombits(0x7fc00002)}))
+ require.Nil(t,
tree.Lookup(PartitionRecord{math.Float64frombits(0x7ff8000000000001)}))
+
+ negativeZeroAggregate := &PartitionAggregate{SpecID: 2}
+ tree.Insert(PartitionRecord{math.Copysign(0, -1)},
negativeZeroAggregate)
+ require.Same(t, negativeZeroAggregate,
tree.Lookup(PartitionRecord{math.Copysign(0, -1)}))
+ require.Nil(t, tree.Lookup(PartitionRecord{float64(0)}))
}
func TestPartitionAggregateTreeLookupPartition(t *testing.T) {
@@ -135,13 +135,13 @@ func TestPartitionAggregateTreeLookupPartition(t
*testing.T) {
1001: []byte{1, 2, 3},
1002: math.NaN(),
}
- record := newPartitionRecord(coercePartition(partition, partitionType),
partitionType)
- aggregate := &partitionAggregate{specID: 1}
- tree := newPartitionAggregateTree()
- tree.insert(record, aggregate)
+ record := NewPartitionRecord(CoercePartition(partition, partitionType),
partitionType)
+ aggregate := &PartitionAggregate{SpecID: 1}
+ tree := NewPartitionAggregateTree()
+ tree.Insert(record, aggregate)
- require.Same(t, aggregate, tree.lookupPartition(partition,
partitionType))
- require.Nil(t, tree.lookupPartition(map[int]any{
+ require.Same(t, aggregate, tree.LookupPartition(partition,
partitionType))
+ require.Nil(t, tree.LookupPartition(map[int]any{
1000: int32(7),
1001: []byte{1, 2, 4},
1002: math.NaN(),
@@ -153,17 +153,17 @@ func TestPartitionAggregateTreeLookupPartition(t
*testing.T) {
1000: int32(7),
1002: math.NaN(),
}
- evolvedRecord := newPartitionRecord(coercePartition(evolvedPartition,
partitionType), partitionType)
- evolvedAggregate := &partitionAggregate{specID: 2}
- tree.insert(evolvedRecord, evolvedAggregate)
+ evolvedRecord := NewPartitionRecord(CoercePartition(evolvedPartition,
partitionType), partitionType)
+ evolvedAggregate := &PartitionAggregate{SpecID: 2}
+ tree.Insert(evolvedRecord, evolvedAggregate)
- require.Same(t, evolvedAggregate,
tree.lookupPartition(evolvedPartition, partitionType))
- require.Same(t, evolvedAggregate, tree.lookup(evolvedRecord))
+ require.Same(t, evolvedAggregate,
tree.LookupPartition(evolvedPartition, partitionType))
+ require.Same(t, evolvedAggregate, tree.Lookup(evolvedRecord))
}
func TestClonePartitionClonesBinaryValues(t *testing.T) {
value := []byte{1, 2, 3}
- cloned := clonePartition(map[int]any{1000: value})
+ cloned := ClonePartition(map[int]any{1000: value})
value[0] = 4
require.Equal(t, []byte{1, 2, 3}, cloned[1000])
diff --git a/table/internal/partition_key.go b/table/internal/partition_key.go
new file mode 100644
index 000000000..e00292e01
--- /dev/null
+++ b/table/internal/partition_key.go
@@ -0,0 +1,57 @@
+// 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 internal
+
+import "math"
+
+type (
+ binaryPartitionKey string
+ float32PartitionKey uint32
+ float64PartitionKey uint64
+)
+
+const (
+ // Canonical NaN payloads make all NaNs of the same width compare equal.
+ // The width-specific key types preserve float width, while using raw
bits
+ // intentionally keeps -0.0 and +0.0 distinct.
+ canonicalFloat32NaNBits uint32 = 0x7fc00000
+ canonicalFloat64NaNBits uint64 = 0x7ff8000000000000
+)
+
+func ComparablePartitionKey(value any) any {
+ switch value := value.(type) {
+ case []byte:
+ return binaryPartitionKey(value)
+ case float32:
+ rawBits := math.Float32bits(value)
+ if math.IsNaN(float64(value)) {
+ rawBits = canonicalFloat32NaNBits
+ }
+
+ return float32PartitionKey(rawBits)
+ case float64:
+ rawBits := math.Float64bits(value)
+ if math.IsNaN(value) {
+ rawBits = canonicalFloat64NaNBits
+ }
+
+ return float64PartitionKey(rawBits)
+ }
+
+ return value
+}
diff --git a/table/internal/partition_record.go
b/table/internal/partition_record.go
new file mode 100644
index 000000000..03aa98100
--- /dev/null
+++ b/table/internal/partition_record.go
@@ -0,0 +1,44 @@
+// 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 internal
+
+import (
+ "slices"
+
+ "github.com/apache/iceberg-go"
+)
+
+type PartitionRecord []any
+
+func (p PartitionRecord) Size() int { return len(p) }
+func (p PartitionRecord) Get(pos int) any { return p[pos] }
+func (p PartitionRecord) Set(pos int, val any) { p[pos] = val }
+
+func NewPartitionRecord(partitionData map[int]any, partitionType
*iceberg.StructType) PartitionRecord {
+ out := make(PartitionRecord, partitionType.NumFields())
+ for i := range partitionType.NumFields() {
+ value := partitionData[partitionType.Field(i).ID]
+ if bytes, ok := value.([]byte); ok {
+ out[i] = slices.Clone(bytes)
+ } else {
+ out[i] = value
+ }
+ }
+
+ return out
+}
diff --git a/table/partition_struct_builder.go
b/table/internal/partition_struct_builder.go
similarity index 91%
rename from table/partition_struct_builder.go
rename to table/internal/partition_struct_builder.go
index bd0f495fb..79e89915e 100644
--- a/table/partition_struct_builder.go
+++ b/table/internal/partition_struct_builder.go
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal
import (
"fmt"
@@ -27,7 +27,7 @@ import (
"github.com/google/uuid"
)
-type partitionStructBuilder struct {
+type PartitionStructBuilder struct {
builder *array.StructBuilder
fields []partitionFieldBuilder
}
@@ -41,15 +41,15 @@ type partitionFieldBuilder struct {
appendValue func(any) error
}
-func newPartitionStructBuilder(
+func NewPartitionStructBuilder(
builder *array.StructBuilder,
partitionType *iceberg.StructType,
-) (*partitionStructBuilder, error) {
+) (*PartitionStructBuilder, error) {
arrowType, ok := builder.Type().(*arrow.StructType)
if !ok {
return nil, fmt.Errorf("partition builder has type %T, want
struct", builder.Type())
}
- lookup, err := newBuilderLookup("partition", arrowType.Fields(),
builder.FieldBuilder)
+ lookup, err := NewBuilderLookup("partition", arrowType.Fields(),
builder.FieldBuilder)
if err != nil {
return nil, err
}
@@ -57,7 +57,7 @@ func newPartitionStructBuilder(
for _, field := range partitionType.Fields() {
expected[field.ID] = struct{}{}
}
- if err := validateBuilderLookup("partition", lookup, expected); err !=
nil {
+ if err := ValidateBuilderLookup("partition", lookup, expected); err !=
nil {
return nil, err
}
@@ -75,10 +75,10 @@ func newPartitionStructBuilder(
fields = append(fields, partitionField)
}
- return &partitionStructBuilder{builder: builder, fields: fields}, nil
+ return &PartitionStructBuilder{builder: builder, fields: fields}, nil
}
-func (b *partitionStructBuilder) append(values map[int]any) error {
+func (b *PartitionStructBuilder) Append(values map[int]any) error {
b.builder.Append(true)
for _, field := range b.fields {
if err := field.appendValue(values[field.id]); err != nil {
@@ -91,7 +91,7 @@ func (b *partitionStructBuilder) append(values map[int]any)
error {
func newPartitionFieldAppender(field partitionFieldBuilder) func(any) error {
appendScalar := func(value any) error {
- sc, err := partitionValueScalar(value, field.typ,
field.arrowType)
+ sc, err := PartitionValueScalar(value, field.typ,
field.arrowType)
if err != nil {
return fmt.Errorf("partition field %q: %w", field.name,
err)
}
@@ -165,7 +165,7 @@ func newTypedPartitionAppender[T any](
}
}
-func partitionValueScalar(value any, typ iceberg.Type, arrowType
arrow.DataType) (scalar.Scalar, error) {
+func PartitionValueScalar(value any, typ iceberg.Type, arrowType
arrow.DataType) (scalar.Scalar, error) {
switch typ.(type) {
case iceberg.DateType:
switch value := value.(type) {
@@ -214,7 +214,7 @@ func partitionValueScalar(value any, typ iceberg.Type,
arrowType arrow.DataType)
return scalar.MakeScalarParam(value, arrowType)
}
-func newBuilderLookup(scope string, fields []arrow.Field, builder func(int)
array.Builder) (map[int]array.Builder, error) {
+func NewBuilderLookup(scope string, fields []arrow.Field, builder func(int)
array.Builder) (map[int]array.Builder, error) {
lookup := make(map[int]array.Builder, len(fields))
for idx, field := range fields {
id := getFieldID(field)
@@ -230,7 +230,7 @@ func newBuilderLookup(scope string, fields []arrow.Field,
builder func(int) arra
return lookup, nil
}
-func validateBuilderLookup(scope string, lookup map[int]array.Builder,
expected map[int]struct{}) error {
+func ValidateBuilderLookup(scope string, lookup map[int]array.Builder,
expected map[int]struct{}) error {
if len(lookup) != len(expected) {
return fmt.Errorf("%s schema has %d fields, want %d", scope,
len(lookup), len(expected))
}
diff --git a/table/partition_struct_builder_test.go
b/table/internal/partition_struct_builder_test.go
similarity index 92%
rename from table/partition_struct_builder_test.go
rename to table/internal/partition_struct_builder_test.go
index 27214ab98..1b83daf6c 100644
--- a/table/partition_struct_builder_test.go
+++ b/table/internal/partition_struct_builder_test.go
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal_test
import (
"math"
@@ -27,6 +27,8 @@ import (
"github.com/apache/arrow-go/v18/arrow/memory"
"github.com/apache/arrow-go/v18/arrow/scalar"
"github.com/apache/iceberg-go"
+ "github.com/apache/iceberg-go/table"
+ "github.com/apache/iceberg-go/table/internal"
"github.com/stretchr/testify/require"
)
@@ -150,7 +152,7 @@ func
TestPartitionStructBuilderAppendsTypedAndFallbackValues(t *testing.T) {
values[i+2] = tt.value
}
builder, partitionBuilder := newPartitionStructBuilderForTest(t, fields)
- require.NoError(t, partitionBuilder.append(values))
+ require.NoError(t, partitionBuilder.Append(values))
partition := builder.NewArray().(*array.Struct)
defer partition.Release()
@@ -165,7 +167,7 @@ func TestPartitionStructBuilderAppendsNullValues(t
*testing.T) {
builder, partitionBuilder := newPartitionStructBuilderForTest(t,
[]iceberg.NestedField{
{ID: 2, Name: "value", Type: iceberg.PrimitiveTypes.Int32},
})
- require.NoError(t, partitionBuilder.append(nil))
+ require.NoError(t, partitionBuilder.Append(nil))
partition := builder.NewArray().(*array.Struct)
defer partition.Release()
@@ -190,7 +192,7 @@ func
TestPartitionStructBuilderScalarFallbackPreservesValidation(t *testing.T) {
builder, partitionBuilder :=
newPartitionStructBuilderForTest(t, []iceberg.NestedField{
{ID: 2, Name: "value", Type: tt.typ},
})
- err := partitionBuilder.append(map[int]any{2: tt.value})
+ err := partitionBuilder.Append(map[int]any{2: tt.value})
if tt.wantErr != "" {
require.ErrorContains(t, err, tt.wantErr)
@@ -207,10 +209,10 @@ func
TestPartitionStructBuilderScalarFallbackPreservesValidation(t *testing.T) {
func newPartitionStructBuilderForTest(
t *testing.T,
fields []iceberg.NestedField,
-) (*array.StructBuilder, *partitionStructBuilder) {
+) (*array.StructBuilder, *internal.PartitionStructBuilder) {
t.Helper()
partitionType := iceberg.NewStructType(fields...)
- schema, err := SchemaToArrowSchema(iceberg.NewSchema(0,
iceberg.NestedField{
+ schema, err := table.SchemaToArrowSchema(iceberg.NewSchema(0,
iceberg.NestedField{
ID: 1, Name: "partition", Type: partitionType, Required: true,
}), nil, true, false)
require.NoError(t, err)
@@ -218,7 +220,7 @@ func newPartitionStructBuilderForTest(
require.True(t, ok)
builder := array.NewStructBuilder(memory.DefaultAllocator, structType)
t.Cleanup(builder.Release)
- partitionBuilder, err := newPartitionStructBuilder(builder,
partitionType)
+ partitionBuilder, err := internal.NewPartitionStructBuilder(builder,
partitionType)
require.NoError(t, err)
return builder, partitionBuilder
@@ -238,8 +240,8 @@ func
TestPartitionStructBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
} {
t.Run(tt.name, func(t *testing.T) {
builder, partitionBuilder :=
newPartitionStructBuilderForTest(t, []iceberg.NestedField{{ID: 2, Name:
"value", Type: tt.typ}})
- require.NoError(t,
partitionBuilder.append(map[int]any{2: tt.value}))
- require.NoError(t, partitionBuilder.append(nil))
+ require.NoError(t,
partitionBuilder.Append(map[int]any{2: tt.value}))
+ require.NoError(t, partitionBuilder.Append(nil))
partition := builder.NewArray().(*array.Struct)
defer partition.Release()
require.True(t, partition.Field(0).IsValid(0))
@@ -252,7 +254,7 @@ func
TestPartitionStructBuilderPreservesEmptyAndSpecialValues(t *testing.T) {
func TestPartitionStructBuilderCopiesBinaryValues(t *testing.T) {
builder, partitionBuilder := newPartitionStructBuilderForTest(t,
[]iceberg.NestedField{{ID: 2, Name: "value", Type:
iceberg.PrimitiveTypes.Binary}})
value := []byte("abc")
- require.NoError(t, partitionBuilder.append(map[int]any{2: value}))
+ require.NoError(t, partitionBuilder.Append(map[int]any{2: value}))
value[0] = 'x'
partition := builder.NewArray().(*array.Struct)
defer partition.Release()
@@ -264,7 +266,7 @@ func TestPartitionValueScalarDecimal(t *testing.T) {
arrowType := &arrow.Decimal128Type{Precision: 10, Scale: 2}
value := iceberg.DecimalLiteral{Val: decimal128.FromI64(123), Scale: 2}
- got, err := partitionValueScalar(value, typ, arrowType)
+ got, err := internal.PartitionValueScalar(value, typ, arrowType)
require.NoError(t, err)
require.Equal(t, value.Val, got.(*scalar.Decimal128).Value)
}
@@ -286,7 +288,7 @@ func
TestPartitionValueScalarRejectsMismatchedPartitionValues(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := partitionValueScalar(tt.value, tt.typ,
tt.arrowType)
+ _, err := internal.PartitionValueScalar(tt.value,
tt.typ, tt.arrowType)
require.ErrorContains(t, err, tt.want)
})
}
diff --git a/table/internal/position_delete_columns.go
b/table/internal/position_delete_columns.go
new file mode 100644
index 000000000..59aa4caa7
--- /dev/null
+++ b/table/internal/position_delete_columns.go
@@ -0,0 +1,80 @@
+// 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 internal
+
+import (
+ "fmt"
+
+ "github.com/apache/arrow-go/v18/arrow"
+ "github.com/apache/arrow-go/v18/arrow/array"
+ "github.com/apache/iceberg-go"
+)
+
+func PositionDeleteColumnIndices(schema *arrow.Schema) (int, int, error) {
+ // Position-delete columns are resolved by their spec-defined names
because
+ // Arrow schemas read from external files do not always retain Iceberg
IDs.
+ requiredColumn := func(name string) (int, error) {
+ indices := schema.FieldIndices(name)
+ if len(indices) != 1 {
+ return 0, fmt.Errorf("%w: position delete file must
contain exactly one %q column, found %d",
+ iceberg.ErrInvalidSchema, name, len(indices))
+ }
+
+ return indices[0], nil
+ }
+
+ filePathIndex, err := requiredColumn("file_path")
+ if err != nil {
+ return 0, 0, err
+ }
+ posIndex, err := requiredColumn("pos")
+ if err != nil {
+ return 0, 0, err
+ }
+
+ return filePathIndex, posIndex, nil
+}
+
+func FilePathValues(values arrow.Array) (arrow.TypedArray[string], error) {
+ switch arr := values.(type) {
+ case *array.Dictionary:
+ wrapped, err := array.NewDictWrapper[string](arr)
+ if err != nil {
+ return nil, fmt.Errorf("%w: file_path column is not
string: %w",
+ iceberg.ErrInvalidSchema, err)
+ }
+
+ return wrapped, nil
+ case arrow.TypedArray[string]:
+ return arr, nil
+ default:
+ return nil, fmt.Errorf("%w: unsupported file_path column type
%s in position delete file",
+ iceberg.ErrInvalidSchema, values.DataType())
+ }
+}
+
+func ValidatePositionDeletePositions(positions *array.Int64) error {
+ for row := range positions.Len() {
+ if position := positions.Value(row); position < 0 {
+ return fmt.Errorf("%w: negative pos %d in position
delete file",
+ iceberg.ErrInvalidSchema, position)
+ }
+ }
+
+ return nil
+}
diff --git a/table/internal/record_batch_size.go
b/table/internal/record_batch_size.go
new file mode 100644
index 000000000..a93abcb78
--- /dev/null
+++ b/table/internal/record_batch_size.go
@@ -0,0 +1,22 @@
+// 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 internal
+
+// RecordBatchSize is the number of rows per Arrow record batch produced by
+// metadata tables and partition statistics.
+const RecordBatchSize = 4096
diff --git a/table/unified_partition_type.go
b/table/internal/unified_partition_type.go
similarity index 89%
rename from table/unified_partition_type.go
rename to table/internal/unified_partition_type.go
index ad3e65af3..7dd663e72 100644
--- a/table/unified_partition_type.go
+++ b/table/internal/unified_partition_type.go
@@ -15,7 +15,7 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal
import (
"fmt"
@@ -26,18 +26,15 @@ import (
iceinternal "github.com/apache/iceberg-go/internal"
)
-// unifiedPartitionType returns the table-wide partition type. It contains the
-// union of partition fields from every spec, which lets metadata tables
-// represent live files written before partition evolution.
-func unifiedPartitionType(metadata Metadata) (*iceberg.StructType, error) {
- return unifiedPartitionTypeWithSchema(metadata,
metadata.CurrentSchema())
-}
-
-func unifiedPartitionTypeWithSchema(
- metadata Metadata,
+// UnifiedPartitionType returns the table-wide partition type for specs,
+// resolved against currentSchema. It contains the union of partition fields
+// from every spec, which lets metadata tables represent live files written
+// before partition evolution.
+func UnifiedPartitionType(
+ specs []iceberg.PartitionSpec,
currentSchema *iceberg.Schema,
) (*iceberg.StructType, error) {
- specs := metadata.PartitionSpecs()
+ specs = slices.Clone(specs)
sort.Slice(specs, func(left, right int) bool {
return specs[left].ID() > specs[right].ID()
})
diff --git a/table/unified_partition_type_test.go
b/table/internal/unified_partition_type_test.go
similarity index 78%
rename from table/unified_partition_type_test.go
rename to table/internal/unified_partition_type_test.go
index de8c1ec86..6d7cab814 100644
--- a/table/unified_partition_type_test.go
+++ b/table/internal/unified_partition_type_test.go
@@ -15,13 +15,12 @@
// specific language governing permissions and limitations
// under the License.
-package table
+package internal
import (
"testing"
"github.com/apache/iceberg-go"
- "github.com/google/uuid"
"github.com/stretchr/testify/require"
)
@@ -36,21 +35,11 @@ func TestUnifiedPartitionTypeUsesAllActiveSpecs(t
*testing.T) {
newSpec := iceberg.NewPartitionSpecID(1, iceberg.PartitionField{
SourceIDs: []int{2}, FieldID: 1001, Name: "category",
Transform: iceberg.IdentityTransform{},
})
- lastPartitionID := 1001
- meta := &metadataV2{commonMetadata: commonMetadata{
- FormatVersion: 2,
- UUID: uuid.New(),
- LastColumnId: 2,
- SchemaList: []*iceberg.Schema{schema},
- CurrentSchemaID: 0,
- Specs: []iceberg.PartitionSpec{oldSpec, newSpec},
- DefaultSpecID: 1,
- LastPartitionID: &lastPartitionID,
- SnapshotRefs: map[string]SnapshotRef{},
- }}
-
- partitionType, err := unifiedPartitionType(meta)
+ specs := []iceberg.PartitionSpec{oldSpec, newSpec}
+ partitionType, err := UnifiedPartitionType(specs, schema)
require.NoError(t, err)
+ // UnifiedPartitionType sorts by spec ID internally; the caller's slice
keeps its order.
+ require.Equal(t, []int{0, 1}, []int{specs[0].ID(), specs[1].ID()})
require.Equal(t, []int{1000, 1001}, []int{
partitionType.Field(0).ID,
partitionType.Field(1).ID,
@@ -66,20 +55,6 @@ func TestUnifiedPartitionTypeRejectsIncompatibleFieldReuse(t
*testing.T) {
iceberg.NestedField{ID: 1, Name: "first", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
iceberg.NestedField{ID: 2, Name: "second", Type:
iceberg.PrimitiveTypes.Int32, Required: true},
)
- metadataFor := func(specs []iceberg.PartitionSpec) Metadata {
- lastPartitionID := 1000
-
- return &metadataV2{commonMetadata: commonMetadata{
- FormatVersion: 2,
- UUID: uuid.New(),
- LastColumnId: 2,
- SchemaList: []*iceberg.Schema{schema},
- CurrentSchemaID: 0,
- Specs: specs,
- DefaultSpecID: specs[len(specs)-1].ID(),
- LastPartitionID: &lastPartitionID,
- }}
- }
field := func(specID, sourceID int, transform iceberg.Transform)
iceberg.PartitionSpec {
return iceberg.NewPartitionSpecID(specID,
iceberg.PartitionField{
SourceIDs: []int{sourceID}, FieldID: 1000, Name:
"part", Transform: transform,
@@ -121,7 +96,7 @@ func TestUnifiedPartitionTypeRejectsIncompatibleFieldReuse(t
*testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
- _, err := unifiedPartitionType(metadataFor(tt.specs))
+ _, err := UnifiedPartitionType(tt.specs, schema)
if tt.valid {
require.NoError(t, err)
@@ -133,6 +108,6 @@ func
TestUnifiedPartitionTypeRejectsIncompatibleFieldReuse(t *testing.T) {
unknown, err := iceberg.ParseTransform("future_transform")
require.NoError(t, err)
- _, err =
unifiedPartitionType(metadataFor([]iceberg.PartitionSpec{field(0, 1, unknown)}))
+ _, err = UnifiedPartitionType([]iceberg.PartitionSpec{field(0, 1,
unknown)}, schema)
require.ErrorIs(t, err, iceberg.ErrInvalidPartitionSpec)
}
diff --git a/table/partition_statistics_v2_v3_test.go
b/table/partition_statistics_v2_v3_test.go
index 6d0d02f59..9983489ca 100644
--- a/table/partition_statistics_v2_v3_test.go
+++ b/table/partition_statistics_v2_v3_test.go
@@ -35,6 +35,7 @@ import (
"github.com/apache/arrow-go/v18/parquet/pqarrow"
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/stretchr/testify/require"
)
@@ -425,18 +426,18 @@ func TestPartitionStatisticsAllMetricOverflows(t
*testing.T) {
spec := partitionedSpec()
for _, tt := range []struct {
name string
- row partitionAggregate
+ row tblutils.PartitionAggregate
content iceberg.ManifestEntryContent
path string
}{
- {"data records", partitionAggregate{dataRecordCount:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
- {"data files", partitionAggregate{dataFileCount:
math.MaxInt32}, iceberg.EntryContentData, "data.parquet"},
- {"data bytes", partitionAggregate{dataFileSize: math.MaxInt64},
iceberg.EntryContentData, "data.parquet"},
- {"position records", partitionAggregate{positionDeleteCount:
math.MaxInt64}, iceberg.EntryContentPosDeletes, "delete.parquet"},
- {"position files", partitionAggregate{positionDeleteFiles:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.parquet"},
- {"equality records", partitionAggregate{equalityDeleteCount:
math.MaxInt64}, iceberg.EntryContentEqDeletes, "delete.parquet"},
- {"equality files", partitionAggregate{equalityDeleteFiles:
math.MaxInt32}, iceberg.EntryContentEqDeletes, "delete.parquet"},
- {"vectors", partitionAggregate{deletionVectorCount:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.puffin"},
+ {"data records", tblutils.PartitionAggregate{DataRecordCount:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
+ {"data files", tblutils.PartitionAggregate{DataFileCount:
math.MaxInt32}, iceberg.EntryContentData, "data.parquet"},
+ {"data bytes", tblutils.PartitionAggregate{DataFileSize:
math.MaxInt64}, iceberg.EntryContentData, "data.parquet"},
+ {"position records",
tblutils.PartitionAggregate{PositionDeleteCount: math.MaxInt64},
iceberg.EntryContentPosDeletes, "delete.parquet"},
+ {"position files",
tblutils.PartitionAggregate{PositionDeleteFiles: math.MaxInt32},
iceberg.EntryContentPosDeletes, "delete.parquet"},
+ {"equality records",
tblutils.PartitionAggregate{EqualityDeleteCount: math.MaxInt64},
iceberg.EntryContentEqDeletes, "delete.parquet"},
+ {"equality files",
tblutils.PartitionAggregate{EqualityDeleteFiles: math.MaxInt32},
iceberg.EntryContentEqDeletes, "delete.parquet"},
+ {"vectors", tblutils.PartitionAggregate{DeletionVectorCount:
math.MaxInt32}, iceberg.EntryContentPosDeletes, "delete.puffin"},
} {
t.Run(tt.name, func(t *testing.T) {
file := partitionStatsFile(t, spec, tt.content,
tt.path, map[int]any{1000: int32(2)}, 1).Build()
@@ -549,29 +550,29 @@ func TestPartitionStatisticsVectorTotalsValidateTargets(t
*testing.T) {
{name: "unknown vector sequence", dataSequence: 1,
vectorSequence: -1, vectorCount: 3, wantUnknown: true},
} {
t.Run(tt.name, func(t *testing.T) {
- row := &partitionAggregate{dataRecordCount: 10}
+ row := &tblutils.PartitionAggregate{DataRecordCount: 10}
vectorRow := row
if tt.differentPartition {
- vectorRow = &partitionAggregate{}
+ vectorRow = &tblutils.PartitionAggregate{}
}
data := make(map[string]partitionStatisticsDataFile)
if !tt.missing {
data["data.parquet"] =
partitionStatisticsDataFile{row: row, count: 10, sequence: tt.dataSequence}
}
vectors :=
map[string][]partitionStatisticsVector{"data.parquet": {{row: vectorRow, count:
tt.vectorCount, sequence: tt.vectorSequence}}}
- unrelated := &partitionAggregate{dataRecordCount: 20}
- allRows := []*partitionAggregate{row, unrelated}
+ unrelated :=
&tblutils.PartitionAggregate{DataRecordCount: 20}
+ allRows := []*tblutils.PartitionAggregate{row,
unrelated}
if vectorRow != row {
allRows = append(allRows, vectorRow)
}
err := finishPartitionStatistics(t.Context(), allRows,
data, vectors, true)
require.NoError(t, err)
- require.Equal(t, int64(20), *unrelated.totalRecordCount)
+ require.Equal(t, int64(20), *unrelated.TotalRecordCount)
if tt.wantUnknown {
- require.Nil(t, row.totalRecordCount)
- require.Nil(t, vectorRow.totalRecordCount)
+ require.Nil(t, row.TotalRecordCount)
+ require.Nil(t, vectorRow.TotalRecordCount)
} else {
- require.Equal(t, int64(7),
*row.totalRecordCount)
+ require.Equal(t, int64(7),
*row.TotalRecordCount)
}
})
}
@@ -752,7 +753,7 @@ func TestPartitionStatisticsV2V3FailureAndEmptySnapshots(t
*testing.T) {
fs, err := tbl.FS(t.Context())
require.NoError(t, err)
_, err = writePartitionStatisticsParquet(ctx,
fs.(iceio.WriteFileIO), "mem://stats/table/metadata/cancelled.parquet",
statsTestPartitionType(),
- []*partitionAggregate{{partition: map[int]any{1000:
int32(2)}}}, version)
+ []*tblutils.PartitionAggregate{{Partition:
map[int]any{1000: int32(2)}}}, version)
require.ErrorIs(t, err, context.Canceled)
_, err = fs.Open(t.Context(),
"mem://stats/table/metadata/cancelled.parquet")
require.Error(t, err)
@@ -797,7 +798,7 @@ func
TestPartitionStatisticsV2V3RemovesFileAfterCloseFailure(t *testing.T) {
failure := errors.New("injected close failure")
path := "mem://stats/table/metadata/failed.parquet"
_, err := writePartitionStatisticsParquet(t.Context(),
partitionStatisticsCloseFailureIO{WriteFileIO: fs, failure: failure}, path,
- statsTestPartitionType(),
[]*partitionAggregate{{partition: map[int]any{1000: int32(2)}, dataRecordCount:
10}}, version)
+ statsTestPartitionType(),
[]*tblutils.PartitionAggregate{{Partition: map[int]any{1000: int32(2)},
DataRecordCount: 10}}, version)
require.ErrorIs(t, err, failure)
_, err = fs.Open(t.Context(), path)
require.Error(t, err, "a failed file must not remain available
for registration")
diff --git a/table/partition_statistics_write.go
b/table/partition_statistics_write.go
index ab46c3573..5218d9f7f 100644
--- a/table/partition_statistics_write.go
+++ b/table/partition_statistics_write.go
@@ -32,6 +32,7 @@ import (
"github.com/apache/arrow-go/v18/parquet/pqarrow"
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
"github.com/twmb/avro/ocf"
)
@@ -171,7 +172,7 @@ func (t *Transaction) ComputePartitionStatistics(ctx
context.Context) (*Partitio
if err := validatePartitionStatisticsSourceTypes(t.tbl.Metadata()); err
!= nil {
return nil, err
}
- partitionType, err := unifiedPartitionType(t.tbl.Metadata())
+ partitionType, err :=
tblutils.UnifiedPartitionType(t.tbl.Metadata().PartitionSpecs(), t.tbl.Schema())
if err != nil {
return nil, fmt.Errorf("partition statistics: %w", err)
}
@@ -320,7 +321,7 @@ func collectPartitionStatistics(
specs []iceberg.PartitionSpec,
formatVersion int,
snapshotTimes map[int64]int64,
-) ([]*partitionAggregate, error) {
+) ([]*tblutils.PartitionAggregate, error) {
specByID := make(map[int32]iceberg.PartitionSpec, len(specs))
for _, spec := range specs {
specByID[int32(spec.ID())] = spec
@@ -330,7 +331,7 @@ func collectPartitionStatistics(
return nil, err
}
- trees := make(map[int32]*partitionAggregateTree)
+ trees := make(map[int32]*tblutils.PartitionAggregateTree)
files := partitionStatisticsFileIndex{paths: make(map[string]string)}
var dataFiles map[string]partitionStatisticsDataFile
if formatVersion == 3 {
@@ -338,7 +339,7 @@ func collectPartitionStatistics(
}
vectors := make(map[string][]partitionStatisticsVector)
exactTotals := true
- rows := make([]*partitionAggregate, 0)
+ rows := make([]*tblutils.PartitionAggregate, 0)
for _, manifest := range manifests {
if err := ctx.Err(); err != nil {
return nil, err
@@ -356,7 +357,7 @@ func collectPartitionStatistics(
}
tree := trees[specID]
if tree == nil {
- tree = newPartitionAggregateTree()
+ tree = tblutils.NewPartitionAggregateTree()
trees[specID] = tree
}
@@ -397,7 +398,7 @@ func collectPartitionStatistics(
if err := validatePartitionStatisticsTuple(spec,
file.FilePath(), values); err != nil {
return nil, err
}
- partition := coercePartition(values, partitionType)
+ partition := tblutils.CoercePartition(values,
partitionType)
for i := range partitionType.NumFields() {
field := partitionType.Field(i)
value := partition[field.ID]
@@ -418,19 +419,19 @@ func collectPartitionStatistics(
return nil, fmt.Errorf("partition field
%q: %w", field.Name, err)
}
}
- row := tree.lookupPartition(partition, partitionType)
+ row := tree.LookupPartition(partition, partitionType)
if row == nil {
- row = &partitionAggregate{
- specID: specID,
- partition: clonePartition(partition),
+ row = &tblutils.PartitionAggregate{
+ SpecID: specID,
+ Partition:
tblutils.ClonePartition(partition),
}
rows = append(rows, row)
- tree.insert(newPartitionRecord(partition,
partitionType), row)
+
tree.Insert(tblutils.NewPartitionRecord(partition, partitionType), row)
}
if timestamp, ok := snapshotTimes[entry.SnapshotID()];
ok &&
- (row.statisticsUpdatedAt == nil || timestamp >
*row.statisticsUpdatedAt) {
- row.statisticsUpdatedAt = new(timestamp)
- row.statisticsUpdatedSnapshot =
new(entry.SnapshotID())
+ (row.StatisticsUpdatedAt == nil || timestamp >
*row.StatisticsUpdatedAt) {
+ row.StatisticsUpdatedAt = new(timestamp)
+ row.StatisticsUpdatedSnapshot =
new(entry.SnapshotID())
}
if entry.Status() == iceberg.EntryStatusDELETED {
continue
@@ -464,7 +465,7 @@ func collectPartitionStatistics(
}
type partitionStatisticsDataFile struct {
- row *partitionAggregate
+ row *tblutils.PartitionAggregate
count int64
sequence int64
}
@@ -526,23 +527,23 @@ func (i *partitionStatisticsFileIndex) add(file
iceberg.DataFile, manifest strin
return vector, nil
}
-func accumulatePartitionStatistics(row *partitionAggregate, file
iceberg.DataFile) error {
+func accumulatePartitionStatistics(row *tblutils.PartitionAggregate, file
iceberg.DataFile) error {
var records *int64
var files *int32
switch file.ContentType() {
case iceberg.EntryContentData:
- records, files = &row.dataRecordCount, &row.dataFileCount
- if row.dataFileSize > math.MaxInt64-file.FileSizeBytes() {
+ records, files = &row.DataRecordCount, &row.DataFileCount
+ if row.DataFileSize > math.MaxInt64-file.FileSizeBytes() {
return fmt.Errorf("%w: partition statistics size
overflow", iceberg.ErrInvalidArgument)
}
- row.dataFileSize += file.FileSizeBytes()
+ row.DataFileSize += file.FileSizeBytes()
case iceberg.EntryContentPosDeletes:
- records, files = &row.positionDeleteCount,
&row.positionDeleteFiles
+ records, files = &row.PositionDeleteCount,
&row.PositionDeleteFiles
if IsDeletionVector(file) {
- files = &row.deletionVectorCount
+ files = &row.DeletionVectorCount
}
case iceberg.EntryContentEqDeletes:
- records, files = &row.equalityDeleteCount,
&row.equalityDeleteFiles
+ records, files = &row.EqualityDeleteCount,
&row.EqualityDeleteFiles
default:
return fmt.Errorf("%w: unsupported statistics file content %d",
iceberg.ErrInvalidArgument, file.ContentType())
}
@@ -555,11 +556,11 @@ func accumulatePartitionStatistics(row
*partitionAggregate, file iceberg.DataFil
return nil
}
-func finishPartitionStatistics(ctx context.Context, rows
[]*partitionAggregate, dataFiles map[string]partitionStatisticsDataFile,
vectors map[string][]partitionStatisticsVector, exactTotals bool) error {
+func finishPartitionStatistics(ctx context.Context, rows
[]*tblutils.PartitionAggregate, dataFiles
map[string]partitionStatisticsDataFile, vectors
map[string][]partitionStatisticsVector, exactTotals bool) error {
for _, row := range rows {
- row.totalRecordCount = nil
+ row.TotalRecordCount = nil
if exactTotals {
- row.totalRecordCount = new(row.dataRecordCount)
+ row.TotalRecordCount = new(row.DataRecordCount)
}
}
for target, targetVectors := range vectors {
@@ -569,30 +570,30 @@ func finishPartitionStatistics(ctx context.Context, rows
[]*partitionAggregate,
data, found := dataFiles[target]
if !found || len(targetVectors) != 1 {
for _, vector := range targetVectors {
- vector.row.totalRecordCount = nil
+ vector.row.TotalRecordCount = nil
}
if found {
- data.row.totalRecordCount = nil
+ data.row.TotalRecordCount = nil
}
continue
}
vector := targetVectors[0]
if vector.row != data.row {
- vector.row.totalRecordCount = nil
- data.row.totalRecordCount = nil
+ vector.row.TotalRecordCount = nil
+ data.row.TotalRecordCount = nil
continue
}
if vector.count > data.count || (data.sequence >= 0 &&
vector.sequence >= 0 && data.sequence > vector.sequence) {
- data.row.totalRecordCount = nil
+ data.row.TotalRecordCount = nil
continue
}
if data.sequence < 0 || vector.sequence < 0 {
- data.row.totalRecordCount = nil
- } else if data.row.totalRecordCount != nil {
- *data.row.totalRecordCount -= vector.count
+ data.row.TotalRecordCount = nil
+ } else if data.row.TotalRecordCount != nil {
+ *data.row.TotalRecordCount -= vector.count
}
}
@@ -612,14 +613,14 @@ func validatePartitionStatisticsTuple(spec
iceberg.PartitionSpec, path string, v
// sortPartitionStatistics obeys the spec's NULL FIRST tuple ordering, not
// inspectPartitionKey's text ordering (where "10" sorts before "2").
// A spec ID only breaks equal tuple ties; it is not the primary sort key.
-func sortPartitionStatistics(rows []*partitionAggregate, partitionType
*iceberg.StructType) error {
+func sortPartitionStatistics(rows []*tblutils.PartitionAggregate,
partitionType *iceberg.StructType) error {
// Collection already validates each partition value before using it as
// an aggregate key. Do not repeat that validation for every output row.
var sortErr error
- slices.SortStableFunc(rows, func(a, b *partitionAggregate) int {
+ slices.SortStableFunc(rows, func(a, b *tblutils.PartitionAggregate) int
{
for i := range partitionType.NumFields() {
field := partitionType.Field(i)
- comp, err :=
comparePartitionStatisticValues(a.partition[field.ID], b.partition[field.ID])
+ comp, err :=
comparePartitionStatisticValues(a.Partition[field.ID], b.Partition[field.ID])
if err != nil {
sortErr = fmt.Errorf("partition field %q: %w",
field.Name, err)
@@ -630,9 +631,9 @@ func sortPartitionStatistics(rows []*partitionAggregate,
partitionType *iceberg.
}
}
switch {
- case a.specID < b.specID:
+ case a.SpecID < b.SpecID:
return -1
- case a.specID > b.specID:
+ case a.SpecID > b.SpecID:
return 1
default:
return 0
@@ -790,7 +791,7 @@ func writePartitionStatisticsParquet(
fs iceio.WriteFileIO,
path string,
partitionType *iceberg.StructType,
- rows []*partitionAggregate,
+ rows []*tblutils.PartitionAggregate,
formatVersion int,
) (_ int64, err error) {
statsSchema, err := PartitionStatisticsSchema(partitionType,
formatVersion)
@@ -821,56 +822,56 @@ func writePartitionStatisticsParquet(
bldr := array.NewRecordBuilder(memory.DefaultAllocator, sc)
defer bldr.Release()
- part, err :=
newPartitionStructBuilder(bldr.Field(0).(*array.StructBuilder), partitionType)
+ part, err :=
tblutils.NewPartitionStructBuilder(bldr.Field(0).(*array.StructBuilder),
partitionType)
if err != nil {
_ = writer.Close()
_ = fw.Close()
return 0, err
}
- for start := 0; start < len(rows); start += recordBatchSize {
+ for start := 0; start < len(rows); start += tblutils.RecordBatchSize {
if err := ctx.Err(); err != nil {
_ = writer.Close()
_ = fw.Close()
return 0, err
}
- end := min(start+recordBatchSize, len(rows))
+ end := min(start+tblutils.RecordBatchSize, len(rows))
for _, row := range rows[start:end] {
- if err := part.append(row.partition); err != nil {
+ if err := part.Append(row.Partition); err != nil {
_ = writer.Close()
_ = fw.Close()
return 0, err
}
- bldr.Field(1).(*array.Int32Builder).Append(row.specID)
-
bldr.Field(2).(*array.Int64Builder).Append(row.dataRecordCount)
-
bldr.Field(3).(*array.Int32Builder).Append(row.dataFileCount)
-
bldr.Field(4).(*array.Int64Builder).Append(row.dataFileSize)
+ bldr.Field(1).(*array.Int32Builder).Append(row.SpecID)
+
bldr.Field(2).(*array.Int64Builder).Append(row.DataRecordCount)
+
bldr.Field(3).(*array.Int32Builder).Append(row.DataFileCount)
+
bldr.Field(4).(*array.Int64Builder).Append(row.DataFileSize)
if formatVersion == 1 {
-
bldr.Field(5).(*array.Int64Builder).Append(row.dataRecordCount)
+
bldr.Field(5).(*array.Int64Builder).Append(row.DataRecordCount)
} else {
-
bldr.Field(5).(*array.Int64Builder).Append(row.positionDeleteCount)
-
bldr.Field(6).(*array.Int32Builder).Append(row.positionDeleteFiles)
-
bldr.Field(7).(*array.Int64Builder).Append(row.equalityDeleteCount)
-
bldr.Field(8).(*array.Int32Builder).Append(row.equalityDeleteFiles)
+
bldr.Field(5).(*array.Int64Builder).Append(row.PositionDeleteCount)
+
bldr.Field(6).(*array.Int32Builder).Append(row.PositionDeleteFiles)
+
bldr.Field(7).(*array.Int64Builder).Append(row.EqualityDeleteCount)
+
bldr.Field(8).(*array.Int32Builder).Append(row.EqualityDeleteFiles)
total := bldr.Field(9).(*array.Int64Builder)
- if row.totalRecordCount == nil {
+ if row.TotalRecordCount == nil {
total.AppendNull()
} else {
- total.Append(*row.totalRecordCount)
+ total.Append(*row.TotalRecordCount)
}
updatedAt :=
bldr.Field(10).(*array.Int64Builder)
updatedSnapshot :=
bldr.Field(11).(*array.Int64Builder)
- if row.statisticsUpdatedAt == nil {
+ if row.StatisticsUpdatedAt == nil {
updatedAt.AppendNull()
updatedSnapshot.AppendNull()
} else {
-
updatedAt.Append(*row.statisticsUpdatedAt)
-
updatedSnapshot.Append(*row.statisticsUpdatedSnapshot)
+
updatedAt.Append(*row.StatisticsUpdatedAt)
+
updatedSnapshot.Append(*row.StatisticsUpdatedSnapshot)
}
if formatVersion == 3 {
-
bldr.Field(12).(*array.Int32Builder).Append(row.deletionVectorCount)
+
bldr.Field(12).(*array.Int32Builder).Append(row.DeletionVectorCount)
}
}
}
diff --git a/table/partition_statistics_write_test.go
b/table/partition_statistics_write_test.go
index fa4b052fb..fbceb8dc6 100644
--- a/table/partition_statistics_write_test.go
+++ b/table/partition_statistics_write_test.go
@@ -36,6 +36,7 @@ import (
"github.com/apache/arrow-go/v18/parquet/pqarrow"
"github.com/apache/iceberg-go"
iceio "github.com/apache/iceberg-go/io"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
"github.com/twmb/avro/ocf"
@@ -112,22 +113,22 @@ func
TestPartitionStatisticValuesNullFirstNumericAndBinary(t *testing.T) {
func TestSortPartitionStatisticsByTupleThenSpecID(t *testing.T) {
pt := statsTestPartitionType()
- rows := []*partitionAggregate{
- {partition: map[int]any{1000: int32(10), 1001: "z"}, specID: 3},
- {partition: map[int]any{1000: int32(2), 1001: "z"}, specID: 4},
- {partition: map[int]any{1000: int32(-1), 1001: "a"}, specID: 1},
- {partition: map[int]any{1000: nil, 1001: "z"}, specID: 2},
- {partition: map[int]any{1000: int32(2), 1001: "z"}, specID: 1},
- {partition: map[int]any{1000: int32(2), 1001: "a"}, specID: 5},
+ rows := []*tblutils.PartitionAggregate{
+ {Partition: map[int]any{1000: int32(10), 1001: "z"}, SpecID: 3},
+ {Partition: map[int]any{1000: int32(2), 1001: "z"}, SpecID: 4},
+ {Partition: map[int]any{1000: int32(-1), 1001: "a"}, SpecID: 1},
+ {Partition: map[int]any{1000: nil, 1001: "z"}, SpecID: 2},
+ {Partition: map[int]any{1000: int32(2), 1001: "z"}, SpecID: 1},
+ {Partition: map[int]any{1000: int32(2), 1001: "a"}, SpecID: 5},
}
require.NoError(t, sortPartitionStatistics(rows, pt))
require.Equal(t, []int32{2, 1, 5, 1, 4, 3}, []int32{
- rows[0].specID, rows[1].specID, rows[2].specID,
- rows[3].specID, rows[4].specID, rows[5].specID,
+ rows[0].SpecID, rows[1].SpecID, rows[2].SpecID,
+ rows[3].SpecID, rows[4].SpecID, rows[5].SpecID,
})
- require.Nil(t, rows[0].partition[1000])
- require.EqualValues(t, -1, rows[1].partition[1000])
- require.EqualValues(t, 10, rows[5].partition[1000])
+ require.Nil(t, rows[0].Partition[1000])
+ require.EqualValues(t, -1, rows[1].Partition[1000])
+ require.EqualValues(t, 10, rows[5].Partition[1000])
}
func TestSortPartitionStatisticsFloatAndUUID(t *testing.T) {
@@ -135,36 +136,36 @@ func TestSortPartitionStatisticsFloatAndUUID(t
*testing.T) {
pt := iceberg.NewStructType(
iceberg.NestedField{ID: 1000, Name: "value", Type:
iceberg.PrimitiveTypes.Float64},
)
- rows := []*partitionAggregate{
- {partition: map[int]any{1000: math.NaN()}, specID: 6},
- {partition: map[int]any{1000: float64(0)}, specID: 3},
- {partition: map[int]any{1000: math.Inf(1)}, specID: 5},
- {partition: map[int]any{1000: math.Copysign(0, -1)},
specID: 2},
- {partition: map[int]any{1000: math.Inf(-1)}, specID: 1},
- {partition: map[int]any{1000:
math.Float64frombits(0xfff8000000000001)}, specID: 7},
+ rows := []*tblutils.PartitionAggregate{
+ {Partition: map[int]any{1000: math.NaN()}, SpecID: 6},
+ {Partition: map[int]any{1000: float64(0)}, SpecID: 3},
+ {Partition: map[int]any{1000: math.Inf(1)}, SpecID: 5},
+ {Partition: map[int]any{1000: math.Copysign(0, -1)},
SpecID: 2},
+ {Partition: map[int]any{1000: math.Inf(-1)}, SpecID: 1},
+ {Partition: map[int]any{1000:
math.Float64frombits(0xfff8000000000001)}, SpecID: 7},
}
require.NoError(t, sortPartitionStatistics(rows, pt))
require.Equal(t, []int32{1, 2, 3, 5, 6, 7}, []int32{
- rows[0].specID, rows[1].specID, rows[2].specID,
- rows[3].specID, rows[4].specID, rows[5].specID,
+ rows[0].SpecID, rows[1].SpecID, rows[2].SpecID,
+ rows[3].SpecID, rows[4].SpecID, rows[5].SpecID,
})
- require.True(t, math.Signbit(rows[1].partition[1000].(float64)))
- require.False(t,
math.Signbit(rows[2].partition[1000].(float64)))
- require.True(t, math.IsNaN(rows[4].partition[1000].(float64)))
+ require.True(t, math.Signbit(rows[1].Partition[1000].(float64)))
+ require.False(t,
math.Signbit(rows[2].Partition[1000].(float64)))
+ require.True(t, math.IsNaN(rows[4].Partition[1000].(float64)))
})
t.Run("uuid", func(t *testing.T) {
pt := iceberg.NewStructType(
iceberg.NestedField{ID: 1000, Name: "value", Type:
iceberg.PrimitiveTypes.UUID},
)
- rows := []*partitionAggregate{
- {partition: map[int]any{1000:
uuid.MustParse("7fffffff-ffff-ffff-0000-000000000000")}, specID: 4},
- {partition: map[int]any{1000:
uuid.MustParse("00000000-0000-0000-7fff-ffffffffffff")}, specID: 3},
- {partition: map[int]any{1000:
uuid.MustParse("80000000-0000-0000-0000-000000000000")}, specID: 1},
- {partition: map[int]any{1000:
uuid.MustParse("00000000-0000-0000-8000-000000000000")}, specID: 2},
+ rows := []*tblutils.PartitionAggregate{
+ {Partition: map[int]any{1000:
uuid.MustParse("7fffffff-ffff-ffff-0000-000000000000")}, SpecID: 4},
+ {Partition: map[int]any{1000:
uuid.MustParse("00000000-0000-0000-7fff-ffffffffffff")}, SpecID: 3},
+ {Partition: map[int]any{1000:
uuid.MustParse("80000000-0000-0000-0000-000000000000")}, SpecID: 1},
+ {Partition: map[int]any{1000:
uuid.MustParse("00000000-0000-0000-8000-000000000000")}, SpecID: 2},
}
require.NoError(t, sortPartitionStatistics(rows, pt))
require.Equal(t, []int32{1, 2, 3, 4}, []int32{
- rows[0].specID, rows[1].specID, rows[2].specID,
rows[3].specID,
+ rows[0].SpecID, rows[1].SpecID, rows[2].SpecID,
rows[3].SpecID,
})
})
}
@@ -173,14 +174,14 @@ func TestPartitionStatisticsParquetWrite(t *testing.T) {
ctx := t.Context()
fs := iceio.NewMemFS()
path := "mem://bucket/table/metadata/v1-stats.parquet"
- rows := []*partitionAggregate{
+ rows := []*tblutils.PartitionAggregate{
{
- specID: 0, partition: map[int]any{1000: int32(-3),
1001: "a"},
- dataRecordCount: 17, dataFileCount: 2, dataFileSize:
2048,
+ SpecID: 0, Partition: map[int]any{1000: int32(-3),
1001: "a"},
+ DataRecordCount: 17, DataFileCount: 2, DataFileSize:
2048,
},
{
- specID: 1, partition: map[int]any{1000: int32(10),
1001: nil},
- dataRecordCount: 3, dataFileCount: 1, dataFileSize: 512,
+ SpecID: 1, Partition: map[int]any{1000: int32(10),
1001: nil},
+ DataRecordCount: 3, DataFileCount: 1, DataFileSize: 512,
},
}
size, err := writePartitionStatisticsParquet(ctx, fs, path,
statsTestPartitionType(), rows, 1)
@@ -245,19 +246,19 @@ func TestCollectPartitionStatisticsFromLiveManifests(t
*testing.T) {
ctx := t.Context()
fs, err := tbl.FS(ctx)
require.NoError(t, err)
- pt, err := unifiedPartitionType(tbl.Metadata())
+ pt, err :=
tblutils.UnifiedPartitionType(tbl.Metadata().PartitionSpecs(), tbl.Schema())
require.NoError(t, err)
rows, err := collectPartitionStatistics(ctx, fs,
*tbl.CurrentSnapshot(), pt, tbl.Metadata().PartitionSpecs(), 1, nil)
require.NoError(t, err)
require.Len(t, rows, 2)
require.NoError(t, sortPartitionStatistics(rows, pt))
- require.Equal(t, int32(2), rows[0].partition[1000])
- require.Equal(t, int64(12), rows[0].dataRecordCount)
- require.Equal(t, int32(2), rows[0].dataFileCount)
- require.Equal(t, int32(10), rows[1].partition[1000])
- require.Equal(t, int64(3), rows[1].dataRecordCount)
- require.Equal(t, int32(1), rows[1].dataFileCount)
+ require.Equal(t, int32(2), rows[0].Partition[1000])
+ require.Equal(t, int64(12), rows[0].DataRecordCount)
+ require.Equal(t, int32(2), rows[0].DataFileCount)
+ require.Equal(t, int32(10), rows[1].Partition[1000])
+ require.Equal(t, int64(3), rows[1].DataRecordCount)
+ require.Equal(t, int32(1), rows[1].DataFileCount)
}
func TestCollectPartitionStatisticsDecimalFromManifest(t *testing.T) {
@@ -293,9 +294,9 @@ func TestCollectPartitionStatisticsDecimalFromManifest(t
*testing.T) {
rows, err := collectPartitionStatistics(t.Context(), fs, snapshot,
partitionType, []iceberg.PartitionSpec{spec}, 1, nil)
require.NoError(t, err)
require.Len(t, rows, 1)
- require.Equal(t, amount, rows[0].partition[1000])
- require.Equal(t, int64(10), rows[0].dataRecordCount)
- require.Equal(t, int32(2), rows[0].dataFileCount)
+ require.Equal(t, amount, rows[0].Partition[1000])
+ require.Equal(t, int64(10), rows[0].DataRecordCount)
+ require.Equal(t, int32(2), rows[0].DataFileCount)
require.NoError(t, sortPartitionStatistics(rows, partitionType))
const statsPath = "mem://stats/decimal-stats.parquet"
@@ -464,7 +465,7 @@ func
TestCollectPartitionStatisticsRejectsDuplicateLiveFiles(t *testing.T) {
})
fs, err := tbl.FS(t.Context())
require.NoError(t, err)
- pt, err := unifiedPartitionType(tbl.Metadata())
+ pt, err :=
tblutils.UnifiedPartitionType(tbl.Metadata().PartitionSpecs(), tbl.Schema())
require.NoError(t, err)
_, err = collectPartitionStatistics(t.Context(), fs,
*tbl.CurrentSnapshot(), pt, tbl.Metadata().PartitionSpecs(), 1, nil)
@@ -493,12 +494,12 @@ func TestPartitionStatisticsEmbeddedManifests(t
*testing.T) {
require.NoError(t, err)
require.Len(t, rows, 3)
require.NoError(t, sortPartitionStatistics(rows, pt))
- require.Nil(t, rows[0].partition[1000])
- require.Equal(t, int32(7), rows[0].specID)
- require.Equal(t, int32(0), rows[1].specID)
- require.Equal(t, int64(10), rows[1].dataRecordCount)
- require.Equal(t, int32(7), rows[2].specID)
- require.Equal(t, int64(20), rows[2].dataRecordCount)
+ require.Nil(t, rows[0].Partition[1000])
+ require.Equal(t, int32(7), rows[0].SpecID)
+ require.Equal(t, int32(0), rows[1].SpecID)
+ require.Equal(t, int64(10), rows[1].DataRecordCount)
+ require.Equal(t, int32(7), rows[2].SpecID)
+ require.Equal(t, int64(20), rows[2].DataRecordCount)
statsPath := "mem://stats/partition-stats.parquet"
_, err = writePartitionStatisticsParquet(t.Context(), fs, statsPath,
pt, rows, 1)
require.NoError(t, err)
diff --git a/table/partitioned_fanout_writer.go
b/table/partitioned_fanout_writer.go
index 5cad5c9fe..74af816bf 100644
--- a/table/partitioned_fanout_writer.go
+++ b/table/partitioned_fanout_writer.go
@@ -36,6 +36,7 @@ import (
"github.com/apache/arrow-go/v18/arrow/extensions"
"github.com/apache/iceberg-go"
"github.com/apache/iceberg-go/internal"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/google/uuid"
"golang.org/x/sync/errgroup"
)
@@ -80,48 +81,11 @@ type partitionExtractionPlan struct {
pathPlan partitionPathPlan
}
-type (
- binaryPartitionKey string
- float32PartitionKey uint32
- float64PartitionKey uint64
-)
-
-const (
- // Canonical NaN payloads make all NaNs of the same width compare equal.
- // The width-specific key types preserve float width, while using raw
bits
- // intentionally keeps -0.0 and +0.0 distinct.
- canonicalFloat32NaNBits uint32 = 0x7fc00000
- canonicalFloat64NaNBits uint64 = 0x7ff8000000000000
-)
-
-func comparablePartitionKey(value any) any {
- switch value := value.(type) {
- case []byte:
- return binaryPartitionKey(value)
- case float32:
- rawBits := math.Float32bits(value)
- if math.IsNaN(float64(value)) {
- rawBits = canonicalFloat32NaNBits
- }
-
- return float32PartitionKey(rawBits)
- case float64:
- rawBits := math.Float64bits(value)
- if math.IsNaN(value) {
- rawBits = canonicalFloat64NaNBits
- }
-
- return float64PartitionKey(rawBits)
- }
-
- return value
-}
-
func partitionValuesEqual(left, right any) bool {
- // Supported partition values are primitive literals; []byte is
converted to
- // a string key and float values are converted to comparable
width-aware keys
- // above. The default branch preserves comparable scalar values.
- return comparablePartitionKey(left) == comparablePartitionKey(right)
+ // Supported partition values are primitive literals.
ComparablePartitionKey
+ // converts []byte to a string key and float values to comparable
+ // width-aware keys, and preserves other comparable scalar values.
+ return tblutils.ComparablePartitionKey(left) ==
tblutils.ComparablePartitionKey(right)
}
func partitionRecordsEqual(left, right partitionRecord) bool {
@@ -762,7 +726,7 @@ func (n *partitionMapNode) child(part any) (any, bool) {
return child, found
default:
- child, found := n.children[comparablePartitionKey(part)]
+ child, found :=
n.children[tblutils.ComparablePartitionKey(part)]
return child, found
}
@@ -794,7 +758,7 @@ func (n *partitionMapNode) setChild(part, child any) {
if n.children == nil {
n.children = make(map[any]any)
}
- n.children[comparablePartitionKey(part)] = child
+ n.children[tblutils.ComparablePartitionKey(part)] = child
}
}
diff --git a/table/pos_delete_partitioned_fanout_writer.go
b/table/pos_delete_partitioned_fanout_writer.go
index ea695e401..3f29db5c5 100644
--- a/table/pos_delete_partitioned_fanout_writer.go
+++ b/table/pos_delete_partitioned_fanout_writer.go
@@ -25,6 +25,7 @@ import (
"github.com/apache/arrow-go/v18/arrow"
"github.com/apache/arrow-go/v18/arrow/array"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"golang.org/x/sync/errgroup"
)
@@ -141,7 +142,7 @@ func (p *positionDeletePartitionedFanoutWriter)
partitionPath(partitionContext p
// fields still present in CurrentSchema. Dropped partition source
columns are assumed to
// be void-transformed per the Iceberg spec.
schema := p.metadata.CurrentSchema()
- data := newPartitionRecord(partitionContext.partitionData,
spec.PartitionType(schema))
+ data := tblutils.NewPartitionRecord(partitionContext.partitionData,
spec.PartitionType(schema))
return spec.PartitionToPath(data, schema), nil
}
diff --git a/table/scanner.go b/table/scanner.go
index e6e8e3cf1..94cea194e 100644
--- a/table/scanner.go
+++ b/table/scanner.go
@@ -37,6 +37,7 @@ import (
"github.com/apache/iceberg-go/internal/scanmetrics"
"github.com/apache/iceberg-go/io"
"github.com/apache/iceberg-go/metrics"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"golang.org/x/sync/errgroup"
)
@@ -123,11 +124,9 @@ func newKeyDefaultMapWrapErr[K comparable, V any](factory
func(K) (V, error)) *k
}
}
-type partitionRecord []any
-
-func (p partitionRecord) Size() int { return len(p) }
-func (p partitionRecord) Get(pos int) any { return p[pos] }
-func (p partitionRecord) Set(pos int, val any) { p[pos] = val }
+// partitionRecord is the positional partition record shared with the
+// metadata-table helpers in table/internal.
+type partitionRecord = tblutils.PartitionRecord
// borrowedPartitionRecord exposes a DataFile's immutable partition map in
// partition-field order without materializing a positional record or cloning
@@ -355,24 +354,10 @@ func flattenClassifiedManifestEntries(results
[]classifiedManifestEntries) *mani
return flattened
}
-func newPartitionRecord(partitionData map[int]any, partitionType
*iceberg.StructType) partitionRecord {
- out := make(partitionRecord, partitionType.NumFields())
- for i := range partitionType.NumFields() {
- value := partitionData[partitionType.Field(i).ID]
- if bytes, ok := value.([]byte); ok {
- out[i] = slices.Clone(bytes)
- } else {
- out[i] = value
- }
- }
-
- return out
-}
-
// GetPartitionRecord converts a DataFile's partition map into a positional
// record ordered by the fields of the given partition struct type.
func GetPartitionRecord(dataFile iceberg.DataFile, partitionType
*iceberg.StructType) iceberg.StructLike {
- return newPartitionRecord(dataFilePartition(dataFile), partitionType)
+ return tblutils.NewPartitionRecord(dataFilePartition(dataFile),
partitionType)
}
func openManifest(ctx context.Context, io io.IO, manifest iceberg.ManifestFile,
diff --git a/table/snapshots_bench_test.go b/table/snapshots_bench_test.go
index 42f8dd887..157386653 100644
--- a/table/snapshots_bench_test.go
+++ b/table/snapshots_bench_test.go
@@ -23,6 +23,7 @@ import (
"testing"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
)
var partitionSummaryBenchmarkResult string
@@ -85,7 +86,7 @@ func BenchmarkSnapshotSummaryPartitionPath(b *testing.B) {
b.ReportAllocs()
for b.Loop() {
snapshotSummaryPathBenchmarkResult =
spec.PartitionToPath(
- newPartitionRecord(partition,
spec.PartitionType(schema)), schema)
+
tblutils.NewPartitionRecord(partition, spec.PartitionType(schema)), schema)
}
})
@@ -128,7 +129,7 @@ func BenchmarkSnapshotSummaryPartitionPathEscaped(b
*testing.B) {
} {
b.Run(tc.name, func(b *testing.B) {
partition := map[int]any{1000: tc.value}
- want :=
spec.PartitionToPath(newPartitionRecord(partition, spec.PartitionType(schema)),
schema)
+ want :=
spec.PartitionToPath(tblutils.NewPartitionRecord(partition,
spec.PartitionType(schema)), schema)
var collector SnapshotSummaryCollector
if got := collector.partitionPath(partition, schema,
spec); got != want {
b.Fatalf("partition path changed: got %q, want
%q", got, want)
@@ -138,7 +139,7 @@ func BenchmarkSnapshotSummaryPartitionPathEscaped(b
*testing.B) {
b.ReportAllocs()
for b.Loop() {
snapshotSummaryPathBenchmarkResult =
spec.PartitionToPath(
- newPartitionRecord(partition,
spec.PartitionType(schema)), schema)
+
tblutils.NewPartitionRecord(partition, spec.PartitionType(schema)), schema)
}
})
diff --git a/table/snapshots_internal_test.go b/table/snapshots_internal_test.go
index a703258c4..af1b98c17 100644
--- a/table/snapshots_internal_test.go
+++ b/table/snapshots_internal_test.go
@@ -21,6 +21,7 @@ import (
"testing"
"github.com/apache/iceberg-go"
+ tblutils "github.com/apache/iceberg-go/table/internal"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
@@ -141,7 +142,7 @@ func TestSnapshotSummaryCollectorPartitionPathParity(t
*testing.T) {
var collector SnapshotSummaryCollector
for _, partition := range partitions {
- want := spec.PartitionToPath(newPartitionRecord(partition,
spec.PartitionType(schema)), schema)
+ want :=
spec.PartitionToPath(tblutils.NewPartitionRecord(partition,
spec.PartitionType(schema)), schema)
assert.Equal(t, want, collector.partitionPath(partition,
schema, spec))
}
require.Len(t, collector.partitionPathPlans, 1)
@@ -150,7 +151,7 @@ func TestSnapshotSummaryCollectorPartitionPathParity(t
*testing.T) {
iceberg.PartitionField{SourceIDs: []int{2}, FieldID: 1100,
Name: "other#text", Transform: iceberg.IdentityTransform{}},
)
otherPartition := map[int]any{1100: "a/b c"}
- want := otherSpec.PartitionToPath(newPartitionRecord(otherPartition,
otherSpec.PartitionType(schema)), schema)
+ want :=
otherSpec.PartitionToPath(tblutils.NewPartitionRecord(otherPartition,
otherSpec.PartitionType(schema)), schema)
assert.Equal(t, want, collector.partitionPath(otherPartition, schema,
otherSpec))
require.Len(t, collector.partitionPathPlans, 2)
@@ -161,7 +162,7 @@ func TestSnapshotSummaryCollectorPartitionPathParity(t
*testing.T) {
)
sameIDPartition := map[int]any{1101: "a/b c"}
want = sameIDSpec.PartitionToPath(
- newPartitionRecord(sameIDPartition,
sameIDSpec.PartitionType(schema)), schema)
+ tblutils.NewPartitionRecord(sameIDPartition,
sameIDSpec.PartitionType(schema)), schema)
assert.Equal(t, want, collector.partitionPath(sameIDPartition, schema,
sameIDSpec))
require.Len(t, collector.partitionPathPlans, 3)
@@ -172,7 +173,7 @@ func TestSnapshotSummaryCollectorPartitionPathParity(t
*testing.T) {
iceberg.NestedField{ID: 3, Name: "integer", Type:
iceberg.PrimitiveTypes.Int32},
iceberg.NestedField{ID: 4, Name: "bytes", Type:
iceberg.PrimitiveTypes.Binary},
)
- want = spec.PartitionToPath(newPartitionRecord(partitions[0],
spec.PartitionType(alternateSchema)), alternateSchema)
+ want = spec.PartitionToPath(tblutils.NewPartitionRecord(partitions[0],
spec.PartitionType(alternateSchema)), alternateSchema)
assert.Equal(t, want, collector.partitionPath(partitions[0],
alternateSchema, spec))
require.Len(t, collector.partitionPathPlans, 4)
}
diff --git a/table/transaction_delete.go b/table/transaction_delete.go
index 5fdb2cdec..47188a92b 100644
--- a/table/transaction_delete.go
+++ b/table/transaction_delete.go
@@ -935,7 +935,7 @@ func (t *Transaction) writePositionDeletesForFiles(ctx
context.Context, fs io.IO
return
}
column := record.Column(0)
- values, err := filePathValues(column)
+ values, err := tblutils.FilePathValues(column)
if err != nil {
record.Release()
yield(nil, err)