iceberg

package
v1.10.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 25, 2026 License: MIT Imports: 18 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package iceberg reads and writes Apache Iceberg v2 table metadata, manifest lists and manifests (the table spec, https://iceberg.apache.org/spec/).

Index

Constants

View Source
const (
	OpAppend    = "append"
	OpDelete    = "delete"
	OpOverwrite = "overwrite"
	OpReplace   = "replace"
)

Snapshot summary operations.

View Source
const (
	StatusExisting = 0
	StatusAdded    = 1
	StatusDeleted  = 2

	ContentData            = 0
	ContentPositionDeletes = 1
	ContentEqualityDeletes = 2
)

Manifest entry statuses and content types from the table spec.

View Source
const (
	// FormatVersion is the only table format version this package writes.
	FormatVersion = 2
	// NoSnapshot is the current-snapshot-id of a table without snapshots.
	NoSnapshot = int64(-1)
	// MainBranch is the default branch ref name.
	MainBranch = "main"
)

Variables

View Source
var (
	ErrColumnExists   = errors.New("column already exists")
	ErrColumnNotFound = errors.New("column not found")
	ErrColumnInUse    = errors.New("column is used by the partition spec")
	ErrBadPromotion   = errors.New("unsupported column type change")
	ErrLastColumn     = errors.New("cannot drop the last column")
)

Schema evolution errors.

View Source
var (
	// ErrInvalidMetadata is returned for a metadata document that is not valid Iceberg table metadata.
	ErrInvalidMetadata = errors.New("invalid iceberg table metadata")
	// ErrNoSnapshot is returned when a snapshot id or timestamp matches no snapshot.
	ErrNoSnapshot = errors.New("iceberg snapshot not found")
)
View Source
var ErrBadBound = errors.New("invalid iceberg bound")

ErrBadBound is returned when a bound or value cannot be serialized for its type.

View Source
var ErrInvalidManifest = errors.New("invalid iceberg manifest")

ErrInvalidManifest is returned for an Avro manifest or manifest list that cannot be decoded.

View Source
var ErrUnsupportedType = errors.New("unsupported iceberg type")

ErrUnsupportedType is returned for a type that cannot be converted or written.

Functions

func AvroTypeOf

func AvroTypeOf(icebergType string) (string, error)

AvroTypeOf is the Avro primitive a value of the given Iceberg primitive is stored as in a manifest.

func CompareBound

func CompareBound(a, b Bound) (int, bool)

CompareBound orders two decoded bounds of the same kind; ok=false when the kinds differ or are unordered.

func EncodeBound

func EncodeBound(icebergType string, v Bound) ([]byte, error)

EncodeBound serializes a value of the Iceberg primitive type (spec Appendix D, single-value serialization). v is int64, float64, string or bool as produced by parsing a result cell.

func EncodeManifest

func EncodeManifest(meta *TableMetadata, spec PartitionSpec, content int, entries []ManifestEntry) ([]byte, error)

EncodeManifest writes a manifest of entries written under spec.

func EncodeManifestList

func EncodeManifestList(snapshotID int64, parent *int64, seq int64, files []ManifestFile) ([]byte, error)

EncodeManifestList writes a manifest list for a snapshot.

func EncodeMetadata

func EncodeMetadata(m *TableMetadata) ([]byte, error)

EncodeMetadata renders the metadata.json document.

func FromHive

func FromHive(hive string) (string, error)

FromHive maps an Athena/Hive column type to an Iceberg primitive type name. Nested types return ErrUnsupportedType; use TypeFromHive for them.

func HiveType

func HiveType(raw jsontext.Value) (string, error)

HiveType renders an Iceberg type as the Athena/Hive type name used in the Glue catalog (long -> bigint, list -> array<..>, struct -> struct<a:int,..>).

func InitialMetadataLocation

func InitialMetadataLocation(location string) string

InitialMetadataLocation names the first metadata file of a new table.

func NestedIDs

func NestedIDs(f Field) map[string]int

NestedIDs maps the logical path of every nested field below a column to its field id (struct members by name, "element" for list items, "key" and "value" for maps), e.g. "tags.element".

func NewSnapshotID

func NewSnapshotID() int64

NewSnapshotID returns a random positive snapshot id.

func PrimitiveName

func PrimitiveName(raw jsontext.Value) string

PrimitiveName returns the primitive type name of a field type ("" for nested types).

func TypeFromHive

func TypeFromHive(hive string, next *int) (jsontext.Value, error)

TypeFromHive converts a Hive/Athena column type, nested ones included, to an Iceberg type, assigning fresh field ids to nested fields from *next onward.

Types

type AppendPlan

type AppendPlan struct {
	Metadata         *TableMetadata
	MetadataLocation string
	Objects          []Object
}

AppendPlan is a prepared append commit: the metadata, manifest and manifest list objects to store, and the metadata location to commit to the catalog.

type Bound

type Bound = any

Bound is a decoded column bound: int64, float64, string or bool.

func DecodeBound

func DecodeBound(icebergType string, b []byte) (Bound, bool)

DecodeBound reverses EncodeBound; types without an ordering the engine uses (decimal, binary, uuid) report ok=false.

type Change

type Change struct {
	RemoveData    map[string]bool
	RemoveDeletes map[string]bool
	Operation     string
	AddData       []DataFile
	AddDeletes    []DataFile
}

Change is one snapshot's worth of file changes.

type ColumnSpec

type ColumnSpec struct {
	Name    string
	Type    string
	Comment string
}

ColumnSpec is a column of a table about to be created.

type DataFile

type DataFile struct {
	Partition   map[string]any
	ValueCounts map[int]int64
	NullCounts  map[int]int64
	LowerBounds map[int][]byte
	UpperBounds map[int][]byte
	Path        string
	Format      string
	EqualityIDs []int
	Content     int
	RecordCount int64
	FileSize    int64
}

DataFile is one data or delete file of a manifest entry.

type Field

type Field struct {
	Name     string         `json:"name"`
	Doc      string         `json:"doc,omitempty"`
	Type     jsontext.Value `json:"type"`
	ID       int            `json:"id"`
	Required bool           `json:"required"`
}

Field is one schema field; Type is a primitive name or a nested type object.

type ManifestEntry

type ManifestEntry struct {
	SnapshotID     *int64
	SequenceNumber *int64
	DataFile       DataFile
	Status         int
}

ManifestEntry is a manifest row.

func ReadManifest

func ReadManifest(data []byte) ([]ManifestEntry, error)

ReadManifest decodes a manifest.

type ManifestFile

type ManifestFile struct {
	Path              string
	Length            int64
	SequenceNumber    int64
	MinSequenceNumber int64
	AddedSnapshotID   int64
	AddedRows         int64
	ExistingRows      int64
	DeletedRows       int64
	SpecID            int
	Content           int
	AddedFiles        int
	ExistingFiles     int
	DeletedFiles      int
}

ManifestFile is a manifest list row.

func ReadManifestList

func ReadManifestList(data []byte) ([]ManifestFile, error)

ReadManifestList decodes a manifest list (v1 and v2 column names).

type ManifestReader

type ManifestReader func(path string) ([]ManifestEntry, error)

ManifestReader loads the entries of the manifest stored at path.

type MetadataLogEntry

type MetadataLogEntry struct {
	MetadataFile string `json:"metadata-file"`
	TimestampMS  int64  `json:"timestamp-ms"`
}

MetadataLogEntry records a previous metadata file.

type NewParams

type NewParams struct {
	Now        time.Time
	Properties map[string]string
	Location   string
	SortOrder  jsontext.Value
	Schema     Schema
	Spec       PartitionSpec
}

NewParams describes a table to create.

type Object

type Object struct {
	Location string
	Body     []byte
}

Object is a file to store alongside a table commit.

type PartitionField

type PartitionField struct {
	Name      string `json:"name"`
	Transform string `json:"transform"`
	SourceID  int    `json:"source-id"`
	FieldID   int    `json:"field-id"`
}

PartitionField is one partition spec field.

type PartitionSpec

type PartitionSpec struct {
	Fields []PartitionField `json:"fields"`
	SpecID int              `json:"spec-id"`
}

PartitionSpec is a partitioning of a table.

type Ref

type Ref struct {
	Type       string `json:"type"`
	SnapshotID int64  `json:"snapshot-id"`
}

Ref is a named snapshot reference.

type Schema

type Schema struct {
	Type               string  `json:"type"`
	Fields             []Field `json:"fields"`
	IdentifierFieldIDs []int   `json:"identifier-field-ids,omitempty"`
	SchemaID           int     `json:"schema-id"`
}

Schema is an Iceberg struct schema.

func SchemaFromColumns

func SchemaFromColumns(cols []ColumnSpec) (Schema, error)

SchemaFromColumns builds a schema with sequential field ids; columns are optional (nullable).

func (Schema) MaxFieldID

func (s Schema) MaxFieldID() int

MaxFieldID is the largest field id in s, nested fields included.

type Snapshot

type Snapshot struct {
	Summary          map[string]string `json:"summary,omitempty"`
	ParentSnapshotID *int64            `json:"parent-snapshot-id,omitempty"`
	SchemaID         *int              `json:"schema-id,omitempty"`
	ManifestList     string            `json:"manifest-list,omitempty"`
	SnapshotID       int64             `json:"snapshot-id"`
	SequenceNumber   int64             `json:"sequence-number"`
	TimestampMS      int64             `json:"timestamp-ms"`
}

Snapshot is one table snapshot.

type SnapshotLogEntry

type SnapshotLogEntry struct {
	TimestampMS int64 `json:"timestamp-ms"`
	SnapshotID  int64 `json:"snapshot-id"`
}

SnapshotLogEntry records when a snapshot became current.

type TableMetadata

type TableMetadata struct {
	Properties map[string]string `json:"properties"`
	Refs       map[string]Ref    `json:"refs,omitempty"`

	TableUUID          string             `json:"table-uuid"`
	Location           string             `json:"location"`
	Schemas            []Schema           `json:"schemas"`
	PartitionSpecs     []PartitionSpec    `json:"partition-specs"`
	SortOrders         []jsontext.Value   `json:"sort-orders"`
	Snapshots          []Snapshot         `json:"snapshots"`
	SnapshotLog        []SnapshotLogEntry `json:"snapshot-log"`
	MetadataLog        []MetadataLogEntry `json:"metadata-log"`
	LastSequenceNumber int64              `json:"last-sequence-number"`
	LastUpdatedMS      int64              `json:"last-updated-ms"`
	CurrentSnapshotID  int64              `json:"current-snapshot-id"`
	FormatVersion      int                `json:"format-version"`
	LastColumnID       int                `json:"last-column-id"`
	CurrentSchemaID    int                `json:"current-schema-id"`
	DefaultSpecID      int                `json:"default-spec-id"`
	LastPartitionID    int                `json:"last-partition-id"`
	DefaultSortOrderID int                `json:"default-sort-order-id"`
	// contains filtered or unexported fields
}

TableMetadata is a table's metadata.json document. Fields this package does not model survive a decode/encode round trip.

func NewTableMetadata

func NewTableMetadata(p NewParams) *TableMetadata

NewTableMetadata builds the v2 metadata of a table with no snapshots.

func ParseMetadata

func ParseMetadata(data []byte) (*TableMetadata, error)

ParseMetadata decodes and validates a metadata.json document.

func (*TableMetadata) AppendSnapshot

func (m *TableMetadata) AppendSnapshot(snap Snapshot, previousMetadataFile string, now time.Time) *TableMetadata

AppendSnapshot returns a copy of m with snap added as the current snapshot of main. previousMetadataFile is recorded in the metadata log.

func (*TableMetadata) CurrentSchema

func (m *TableMetadata) CurrentSchema() Schema

CurrentSchema is the table's current schema.

func (*TableMetadata) CurrentSnapshot

func (m *TableMetadata) CurrentSnapshot() (Snapshot, bool)

CurrentSnapshot returns the current snapshot, if the table has one.

func (*TableMetadata) DefaultSpec

func (m *TableMetadata) DefaultSpec() PartitionSpec

DefaultSpec is the spec new data is written with.

func (*TableMetadata) ExpireSnapshots

func (m *TableMetadata) ExpireSnapshots(keep func(Snapshot) bool) []Snapshot

ExpireSnapshots drops the snapshots keep rejects (never the current one) and returns them; log entries and refs that pointed at them go too.

func (*TableMetadata) MarshalJSON

func (m *TableMetadata) MarshalJSON() ([]byte, error)

MarshalJSON encodes the modeled members over the preserved extras.

func (*TableMetadata) NextMetadataLocation

func (m *TableMetadata) NextMetadataLocation() string

NextMetadataLocation names this metadata's own file, numbered by its metadata-log length.

func (*TableMetadata) PlanAppend

func (m *TableMetadata) PlanAppend(
	currentLocation string, prev []ManifestFile, files []DataFile, now time.Time,
) (*AppendPlan, error)

PlanAppend prepares a commit appending files to the table. currentLocation is the metadata file m was read from; prev are the current snapshot's manifests.

func (*TableMetadata) PlanCommit

func (m *TableMetadata) PlanCommit(
	currentLocation string, prev []ManifestFile, read ManifestReader, ch Change, now time.Time,
) (*AppendPlan, error)

PlanCommit prepares a snapshot applying ch to the table's current manifests prev. Manifests holding removed files are rewritten (removed entries become DELETED, the rest EXISTING); read is only needed when ch removes files.

func (*TableMetadata) PlanMetadataUpdate

func (m *TableMetadata) PlanMetadataUpdate(
	currentLocation string, mutate func(next *TableMetadata) error, now time.Time,
) (*AppendPlan, error)

PlanMetadataUpdate prepares a commit that changes only the metadata (schema, properties, retained snapshots): mutate edits a copy of m.

func (*TableMetadata) SchemaByID

func (m *TableMetadata) SchemaByID(id int) (Schema, bool)

SchemaByID returns the schema with the given id.

func (*TableMetadata) SetSchema

func (m *TableMetadata) SetSchema(s Schema)

SetSchema makes s a new current schema of m (an update copy).

func (*TableMetadata) SnapshotAsOf

func (m *TableMetadata) SnapshotAsOf(t time.Time) (Snapshot, error)

SnapshotAsOf returns the snapshot that was current at t: the last snapshot-log entry at or before t.

func (*TableMetadata) SnapshotByID

func (m *TableMetadata) SnapshotByID(id int64) (Snapshot, bool)

SnapshotByID returns the snapshot with the given id.

func (*TableMetadata) SpecByID

func (m *TableMetadata) SpecByID(id int) (PartitionSpec, bool)

SpecByID returns the partition spec with the given id.

func (*TableMetadata) TrimMetadataLog

func (m *TableMetadata) TrimMetadataLog(maxKeep int) []MetadataLogEntry

TrimMetadataLog keeps the newest max previous-metadata entries and returns the dropped ones.

func (*TableMetadata) UnmarshalJSON

func (m *TableMetadata) UnmarshalJSON(b []byte) error

UnmarshalJSON decodes a v1 or v2 document and keeps unmodeled members.

func (*TableMetadata) WithColumn

func (m *TableMetadata) WithColumn(s Schema, name, hiveType, doc string) (Schema, int, error)

WithColumn returns s with a new optional column using the m field id.

func (*TableMetadata) WithMovedColumn

func (m *TableMetadata) WithMovedColumn(s Schema, name string, first bool, after string) (Schema, error)

WithMovedColumn returns s with the column moved first or after another column.

func (*TableMetadata) WithRenamedColumn

func (m *TableMetadata) WithRenamedColumn(s Schema, from, to, hiveType string) (Schema, error)

WithRenamedColumn returns s with the column renamed; a non-empty hiveType also promotes its type.

func (*TableMetadata) WithoutColumn

func (m *TableMetadata) WithoutColumn(s Schema, name string) (Schema, error)

WithoutColumn returns s without the named column; partition source columns cannot be dropped.

type Transform

type Transform struct {
	Name  string
	Width int
}

Transform is a parsed partition transform.

func ParseTransform

func ParseTransform(s string) (Transform, error)

ParseTransform parses identity, year, month, day, hour, void, bucket[N] and truncate[W].

func (Transform) Apply

func (t Transform) Apply(source string, raw *string) (any, error)

Apply transforms the textual value of a source column. A nil result is null. Results are bool, int32, int64, float32, float64 or string.

func (Transform) ResultType

func (t Transform) ResultType(source string) string

ResultType is the Iceberg type of the transform's output for a source type.

func (Transform) String

func (t Transform) String() string

String renders the transform as it appears in a partition spec.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL