vortex

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 26, 2026 License: MIT Imports: 36 Imported by: 0 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.

README

vortex-go

Build Coverage Go Reference Go License Site

A pure Go reader and writer for the Vortex columnar file format.

The site, with how to use it and how it compares with the Rust implementation: https://fclairamb.github.io/vortex-go/.

Goals

Ranked. The details and the "done when" lists are in docs/goals.md.

  1. Easy to use. A file to Go structs, or Go structs to a file, in a few lines and no configuration.
  2. Correct. The Rust implementation is the judge, for what we read and for what we write.
  3. Complete. Every encoding, layout and type of the upstream core edition.
  4. Fast, without allocation. A running scan or writer allocates nothing.
  5. Self-contained. No cgo. The standard library, plus klauspost/compress for zstd.
  6. 100% statement coverage. No exclusion.

Install

go get github.com/fclairamb/vortex-go

Go 1.26 or later. The only dependency is klauspost/compress, for zstd.

Example

Read the rows of a file into structs. This block is copied from ExampleRows in example_test.go by go generate, and a test keeps it at 10 lines or fewer.

f, err := vortex.OpenFile("testdata/fixtures/0.95.0/extra/default_ints.vortex")
if err != nil {
    log.Fatal(err)
}
defer f.Close()
type Row struct {
    Sorted sql.Null[int64] `vortex:"sorted"`
}
for r, err := range vortex.Rows[Row](context.Background(), f, vortex.Query{Rows: vortex.Range{End: 3}}) {
    if err != nil {
        log.Fatal(err)
    }
    fmt.Println(r.Sorted.V)
}

Columns, filters, and writing (NewWriter for columns, NewRowWriter for structs) have an Example function each. The API is in api.txt, the reasons for its shape in docs/interface.md.

Releases read

The files of every published release are read, and checked against the reference reader.

Reads the fixtures of every published release, 30 of them, from 0.64.0 to 0.95.0, checked every night against the reference reader.

Support matrix

What the target edition of the pinned release contains, and what this package reads and writes. Generated from the decoder and encoder registries, never written by hand.

Kind Identifier Read Written
aggregate vortex.bounded_max yes yes
aggregate vortex.bounded_min yes yes
aggregate vortex.max yes yes
aggregate vortex.min yes yes
aggregate vortex.nan_count yes yes
aggregate vortex.null_count yes yes
array fastlanes.bitpacked yes yes
array fastlanes.for yes yes
array fastlanes.rle yes yes
array vortex.alp yes yes
array vortex.alprd yes yes
array vortex.bool yes yes
array vortex.bytebool yes yes
array vortex.chunked yes yes
array vortex.constant yes yes
array vortex.datetimeparts yes yes
array vortex.decimal yes yes
array vortex.decimal_byte_parts yes yes
array vortex.dict yes yes
array vortex.ext yes yes
array vortex.fixed_size_list yes yes
array vortex.fsst yes yes
array vortex.list yes yes
array vortex.listview yes yes
array vortex.map yes yes
array vortex.masked yes yes
array vortex.null yes yes
array vortex.onpair yes yes
array vortex.parquet.variant yes yes
array vortex.pco yes yes
array vortex.primitive yes yes
array vortex.runend yes yes
array vortex.sequence yes yes
array vortex.sparse yes yes
array vortex.struct yes yes
array vortex.varbin yes yes
array vortex.varbinview yes yes
array vortex.variant yes yes
array vortex.zigzag yes yes
array vortex.zstd yes yes
dtype vortex.date yes yes
dtype vortex.time yes yes
dtype vortex.timestamp yes yes
dtype vortex.uuid yes yes
layout vortex.chunked yes yes
layout vortex.dict yes yes
layout vortex.flat yes yes
layout vortex.stats yes yes
layout vortex.struct yes yes
layout vortex.zoned yes yes

Some identifiers are read and never written, each for a reason: see the writer section of docs/goals.md.

Speed

docs/benchmarks.md says how the numbers are made. They are recorded on every merge to main, with the Rust reference measured on the same machine, in the bench-data branch. make bench runs the Go benchmarks, make bench-json all three harnesses.

Limits

  • No query engine: projection and filters only, no joins, no aggregations.
  • No Arrow in the core module, no preview or unstable edition, no third-party encodings.
  • Our files are not byte-identical to the Rust writer's: the format leaves the choice of encodings to the writer. They are at most 10% larger on TPC-H and ClickBench.

See the non-goals in docs/goals.md.

How it is tested

docs/testing.md says how each goal is checked: the corpus of files written by the reference implementation, the oracle that gives the expected values, the check of our writer by the reference reader, the allocation tests and the gates.

make check

Following upstream

.vortex-version pins the upstream release we follow. Renovate opens a PR on each new release. See docs/upstream-update.md.

License

MIT, see LICENSE.

Documentation

Overview

Package vortex reads and writes files in the Vortex columnar format.

Open and OpenFile read the trailer, the footer and the schema of a file. Scan reads columns of numbers, booleans, strings, binaries, decimals, lists, maps and structs, batch by batch, for the columns, the row range and the filter of a Query, and skips what the statistics of the file rule out. Rows reads the same rows into Go structs. NewWriter writes a file from a Schema and Data, in chunks of 8,192 rows, with zone statistics and dictionaries, and the encodings of each chunk picked by a compressor, like the reference writer, and NewRowWriter writes a slice of structs. The goals are in docs/goals.md, the planned interface in docs/interface.md and the test plan in docs/testing.md.

Index

Examples

Constants

View Source
const (
	// MaxMetadataEntries is the number of metadata entries a file may hold.
	MaxMetadataEntries = 16
	// MaxMetadataKeyBytes is the length of a metadata key, in bytes of UTF-8.
	MaxMetadataKeyBytes = 64
)

The limits of the user metadata of a file, the ones of the reference (MAX_METADATA_SEGMENTS and MAX_METADATA_KEY_BYTES): its writer refuses more, its reader refuses a file with more.

Variables

View Source
var (
	// ErrNotVortex means the file does not start and end with the Vortex magic, or is too short.
	ErrNotVortex = errors.New("vortex: not a Vortex file")
	// ErrUnsupportedVersion means the file has a format version this package does not read.
	ErrUnsupportedVersion = errors.New("vortex: unsupported format version")
	// ErrCorrupt means a part of the file is out of bounds or malformed.
	ErrCorrupt = errors.New("vortex: corrupt file")
)

The errors Open returns, to test with errors.Is. Their messages carry the byte offset.

View Source
var ErrDecimalRange = errors.New("vortex: decimal out of the range of 256 bits")

ErrDecimalRange reports a value that does not fit in 256 bits.

View Source
var ErrWriterClosed = errors.New("vortex: the writer is closed")

ErrWriterClosed is returned by Write after Close.

Functions

func Rows

func Rows[T any](ctx context.Context, f *File, q Query) iter.Seq2[T, error]

Rows reads the rows of the file that meet the query into values of T, a struct, batch by batch, and yields them one by one. The columns it reads come from the fields of T, so the query only selects rows: the scan is the one of File.Scan.

A field takes the column named by its tag, vortex:"name", else its own name. The tag vortex:"-" skips the field, vortex:"name,optional" leaves the field at its zero value when the file has no such column. Unexported fields are skipped and embedded structs are flattened. The Go type of a field must be the one the column type calls for, with no widening:

  • bool, the numbers (int and uint are 64 bits), and float32 for a f16 column;
  • vortex.Decimal for a decimal, or int64 when its precision is 18 or less;
  • string (a copy, see below) or []byte (a view, valid in the loop body) for utf8, []byte for binary;
  • time.Time for a date and a timestamp (UTC unless the type has a zone), time.Duration since midnight for a time, or their storage integer;
  • [16]byte for a uuid;
  • a struct for a struct, []X for a list, [N]X or []X for a fixed-size list, map[K]V for a map, and any for a variant (see Column.Variant).

A nullable column needs sql.Null[X] or *X; a column that is not nullable takes those and the plain type. A column of type null has no Go type: leave its field out.

A field whose type is a number, a bool, a decimal, a time, a uuid, a string or a []byte, plain or in sql.Null, is filled without allocating for the row. Pointers, slices, maps and variants allocate for each row.

The strings of such a field share one block per batch, a copy of their bytes that the garbage collector owns, never the memory of the scan or of a mapped file: they stay valid after the loop. The block is at most the bytes of the strings of that field in the batch (8192 rows at most), and one string kept keeps its whole block alive: use strings.Clone to keep a few strings of many batches.

A field that does not fit its column, a missing column, a T that is not a struct, and every error of Scan, come back as the error of the iteration, and the loop ends. A field problem is found before any data is read.

Example

Read the rows of a file into structs. A nullable column goes into a sql.Null field.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	f, err := vortex.OpenFile("testdata/fixtures/0.95.0/extra/default_ints.vortex")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	type Row struct {
		Sorted sql.Null[int64] `vortex:"sorted"`
	}
	for r, err := range vortex.Rows[Row](context.Background(), f, vortex.Query{Rows: vortex.Range{End: 3}}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(r.Sorted.V)
	}
}
Output:
1000
1001
1002
Example (Filter)

Read the rows that meet a filter. The statistics of the file skip the zones that cannot hold a row, and no row is returned that does not match.

package main

import (
	"context"
	"database/sql"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	f, err := vortex.OpenFile("testdata/fixtures/0.95.0/extra/default_ints.vortex")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	type Row struct {
		Sorted sql.Null[int64] `vortex:"sorted"`
	}
	q := vortex.Query{Filter: vortex.Col("sorted").Lt(1003), Rows: vortex.Range{End: 10}}
	for r, err := range vortex.Rows[Row](context.Background(), f, q) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(r.Sorted.V)
	}
}
Output:
1000
1001
1002

func Values

func Values[T Number](c *Column) ([]T, error)

Values returns the values of a numeric column as a slice of T, null rows included (their value is unspecified: check Null). It returns an error, naming both types, when the column is not a T. A f16 column is read as float32. The slice is a view, valid for the iteration.

Types

type Batch

type Batch struct {
	// contains filtered or unexported fields
}

Batch is a group of rows of the columns of a scan. It and its columns are valid for one iteration of the loop.

func (*Batch) Col

func (b *Batch) Col(i int) *Column

Col returns the column i of the batch, in the order the columns were asked for. It panics when i is out of range.

func (*Batch) Len

func (b *Batch) Len() int

Len is the number of rows of the batch.

type Column

type Column struct {
	// contains filtered or unexported fields
}

Column is a view of the values of one column in a batch.

func (*Column) Bool

func (c *Column) Bool(i int) bool

Bool returns the value of row i of a Bool column. It panics when the column is of another type, and when i is out of range.

func (*Column) Bytes

func (c *Column) Bytes(i int) []byte

Bytes returns the bytes of row i of a Utf8, Binary or UUID column: a view, valid until the next batch. It panics when the column is of another type, and when i is out of range.

func (*Column) Decimal

func (c *Column) Decimal(i int) Decimal

Decimal returns the unscaled value of row i of a Decimal column, whatever its precision and the width it is stored at. It panics when the column is of another type, and when i is out of range.

func (*Column) Elems

func (c *Column) Elems() *Column

Elems returns the elements of a List, FixedSizeList or Map column, all the rows' together. For a map, they are structs of two fields, the key and the value. List gives the range of a row. It panics when the column is of another type.

func (*Column) Field

func (c *Column) Field(i int) *Column

Field returns the field i of a Struct column. It panics when the column is of another type, and when i is out of range.

func (*Column) List

func (c *Column) List(i int) (start, end int)

List returns the range of Elems that holds row i of a List, FixedSizeList or Map column: the elements from start to end, end excluded. Ranges of different rows may overlap. It panics when the column is of another type, and when i is out of range.

func (*Column) Null

func (c *Column) Null(i int) bool

Null reports whether row i is null. It panics when i is out of range.

func (*Column) Type

func (c *Column) Type() Type

Type is the logical type of the column.

func (*Column) Variant

func (c *Column) Variant(i int) (any, error)

Variant decodes row i of a Variant column, a null row being nil. The value is nil, a bool, an int64, a float64, a string, a []byte, a time.Time (a date, a time of day on 1970-01-01, or a timestamp, in UTC), a VariantDecimal, a []any or a map[string]any. Every call allocates: the result is a copy, valid after the batch. An error means the value of the file is damaged. It panics when the column is not a Variant, and when i is out of range.

type Compression

type Compression uint8

Compression is how much effort the writer spends to make the file smaller.

const (
	// Default is the level to use when there is no reason to pick another: the compressor
	// picks the lightweight encodings of each chunk (bit-packing, frame of reference,
	// dictionaries, run-end, ALP, FSST...), as the reference writer does.
	Default Compression = iota
	// Compact favors a small file over the time to write it: zstd is a candidate too, for
	// the numbers and the strings. Its structure is smaller too: a chunk carries no
	// statistics of its own, a column of one zone has no table of zones, and a file that a
	// reader reads whole in its first read (about 64 KiB) has no file statistics.
	Compact
	// None writes the values as they are, in plain arrays.
	None
)

The compression levels.

type Data

type Data struct {
	// contains filtered or unexported fields
}

Data is the values of one column, in the shape Go holds them. Build one with Of, OfBools, OfStrings, OfBytes, OfDecimals, OfNulls, OfStruct or OfList. Which Data a column takes is set by its type, see Writer. A Data refers to the slices it was made from: the writer reads them during Write and keeps no reference afterwards.

func Of

func Of[T Number](v []T) Data

Of is the values of a column of numbers: Int8 to Float64, the storage of a date, a time or a timestamp (int32 for a date in days and for a time in seconds or milliseconds, else int64), and the 16 bits of a Float16 as uint16.

func OfBools

func OfBools(v []bool) Data

OfBools is the values of a bool column.

func OfBytes

func OfBytes(v [][]byte) Data

OfBytes is the values of a binary or utf8 column, and of a uuid column, whose values are 16 bytes each.

func OfDecimals

func OfDecimals(v []Decimal) Data

OfDecimals is the values of a decimal column: the unscaled values.

func OfList

func OfList(offsets []int, elems Data) Data

OfList is the values of a list, a fixed-size list or a map column. Row i is the elements offsets[i] to offsets[i+1] of elems, so offsets has one more value than there are rows and never decreases. For a fixed-size list the offsets are regular, 0, size, 2*size... For a map elems is OfStruct(keys, values).

func OfNulls

func OfNulls(n int) Data

OfNulls is a column of the null type: n rows, all null.

func OfStrings

func OfStrings(v []string) Data

OfStrings is the values of a utf8 or binary column.

func OfStruct

func OfStruct(fields ...Data) Data

OfStruct is the values of a struct column: one Data per field, of the same length.

func OfVariants

func OfVariants(vals []any) Data

OfVariants is the values of a Variant column, one of: nil (a null row), bool, any Go integer (an unsigned one up to the largest int64), float32, float64, string, []byte, time.Time (a timestamp, in microseconds, or in nanoseconds when it has a finer part), VariantDecimal, []any and map[string]any of these, up to 128 levels deep. Another Go type is an error of Write that names the type and the row.

func (Data) Nulls

func (d Data) Nulls(null []bool) Data

Nulls returns the Data with these rows marked null: null[i] is true when row i is null. It has as many values as the Data has rows. A column that is not nullable takes none.

type Decimal

type Decimal struct {
	// contains filtered or unexported fields
}

Decimal is the unscaled value of a decimal of any precision, on 256 bits in two's complement: 32 bytes, no pointer. The scale is in the Type of the column, not in each value: Text takes it. The representation is unique, so == and Cmp agree on equality; Cmp also orders.

func DecimalFromBig

func DecimalFromBig(v *big.Int) (Decimal, error)

DecimalFromBig returns the decimal whose unscaled value is v. It returns an error when v does not fit in 256 bits, that is when it is outside -2^255 to 2^255-1.

func DecimalFromInt64

func DecimalFromInt64(v int64) Decimal

DecimalFromInt64 returns the decimal whose unscaled value is v.

func (Decimal) Big

func (d Decimal) Big() *big.Int

Big returns the value as a new big.Int.

func (Decimal) Cmp

func (d Decimal) Cmp(o Decimal) int

Cmp compares the values: -1 when d is less than o, 0 when equal, +1 when greater.

func (Decimal) Int64

func (d Decimal) Int64() (int64, bool)

Int64 returns the value as an int64, and false when it does not fit.

func (Decimal) Text

func (d Decimal) Text(scale int) string

Text prints the value with the point scale digits from the right: the sign when negative, the digits, no exponent. A negative scale adds zeros: the value is multiplied by 10^-scale.

type Expr

type Expr struct {
	// contains filtered or unexported fields
}

Expr is a filter: a small tree of comparisons of columns with Go values, and of And, Or and Not. The zero Expr keeps every row. Build one with Col and the methods of Ref.

A comparison with a null is unknown, like in SQL, and And, Or and Not are three-valued: a row is kept only when the filter is true for it. IsNull is never unknown. For the floats, NaN equals nothing (not even itself), is neither less nor greater than anything, and so is different from everything, like in Go.

The literals are Go values: any integer or float type, bool, string (for a Utf8 column), []byte (Binary, UUID), Decimal, time.Time (date and timestamp) and time.Duration (time), compared exactly even when finer than the unit of the column (Eq never matches then). An integer can be compared with a float column. The filter is checked against the schema before any read: a literal that does not fit the column, and for Eq, Ne and In an integer out of the range of the column, are errors.

func And

func And(e ...Expr) Expr

And is true when every expression is. With none, it keeps every row.

func Not

func Not(e Expr) Expr

Not is true when e is false, false when e is true and unknown when e is.

func Or

func Or(e ...Expr) Expr

Or is true when one of the expressions is. With none, it keeps no row.

type Field

type Field struct {
	Name string
	Type Type
}

Field is a named field of a struct.

type File

type File struct {
	// contains filtered or unexported fields
}

File is an open Vortex file. It is safe for concurrent use.

func Open

func Open(r io.ReaderAt, size int64) (*File, error)

Open reads the trailer, the footer and the schema of the Vortex file in r, which holds size bytes. It reads the last 64 KiB in one call, and one more range when the footer reaches further back. A file larger than 64 KiB costs one more read, for its first bytes. The caller keeps r open for as long as the File is used.

func OpenFile

func OpenFile(path string) (*File, error)

OpenFile opens the Vortex file at path. Close it when done.

func OpenMapped

func OpenMapped(path string) (*File, error)

OpenMapped opens the Vortex file at path like OpenFile does, and maps it in memory: a scan reads the segments where they are, without a copy, so a scan that reads a part of the file (some columns, a range of rows, the rows a filter keeps) only touches that part. Close it when done.

It is for a local file that nothing truncates while it is read. The operating system reports a mapped byte that it cannot read, a truncated file or a failing disk, by stopping the process, where OpenFile returns an error. The columns of a batch are views of the file: they are not read after Close, which gives the memory back once the scans still running have ended, each with an error that wraps os.ErrClosed.

Where the platform cannot map a file, or refuses to map this one, OpenMapped is OpenFile.

func (*File) Close

func (f *File) Close() error

Close closes the file that OpenFile opened: a scan still running returns an error that wraps os.ErrClosed. It does nothing for a File made by Open. A second call returns nil.

func (*File) Metadata added in v0.2.0

func (f *File) Metadata(key string) ([]byte, bool, error)

Metadata returns the value of a key of the metadata of the file, and whether the file has it. The value is a new slice, the caller's to keep. A value is read with the rest of the end of the file at Open when it lies there, as the small ones the writer stores just before the footer do; another one is read now, from the reader of the file, and the error is the one of that read. After Close, that read returns an error that wraps os.ErrClosed.

Example

Store values that are not rows in the file: a version known up front, an index known once the rows are written. The reader gets them back by their key.

package main

import (
	"bytes"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	type Row struct {
		Query int64  `vortex:"query"`
		Data  string `vortex:"data"`
	}
	var buf bytes.Buffer
	w := vortex.NewRowWriter[Row](&buf, vortex.WriteOptions{
		Metadata: map[string][]byte{"schema.version": []byte("3")},
	})
	if _, err := w.Write([]Row{{1, "a"}, {1, "b"}, {2, "c"}}); err != nil {
		log.Fatal(err)
	}
	if err := w.SetMetadata("query_offsets", []byte(`{"1":0,"2":2}`)); err != nil {
		log.Fatal(err)
	}
	if err := w.Close(); err != nil {
		log.Fatal(err)
	}

	f, err := vortex.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		log.Fatal(err)
	}
	for _, key := range f.MetadataKeys() {
		v, _, err := f.Metadata(key)
		if err != nil {
			log.Fatal(err)
		}
		fmt.Printf("%s: %s\n", key, v)
	}
}
Output:
query_offsets: {"1":0,"2":2}
schema.version: 3

func (*File) MetadataKeys added in v0.2.0

func (f *File) MetadataKeys() []string

MetadataKeys returns the keys of the metadata of the file, sorted. A file holds at most MaxMetadataEntries of them.

func (*File) NumRows

func (f *File) NumRows() int64

NumRows returns the number of rows of the file.

func (*File) Scan

func (f *File) Scan(ctx context.Context, q Query, columns ...string) iter.Seq2[*Batch, error]

Scan reads the columns of the file that meet the query, batch by batch, in order, on the calling goroutine. A batch has at most 8,192 rows and is dense: its Len is the number of rows kept, and a batch without any is not returned. The batch has the columns that are named, in that order, and every column in the order of the schema when none is. A name is a top-level column; the fields of a struct come with Column.Field. A column that only the filter needs is read and not returned.

An unknown column, an invalid range, or a filter that does not fit the schema is the error of the first iteration, before any read.

Example

Read columns, batch by batch, without structs. Values copies a numeric column into a slice.

package main

import (
	"context"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	f, err := vortex.OpenFile("testdata/fixtures/0.95.0/extra/default_ints.vortex")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	for b, err := range f.Scan(context.Background(), vortex.Query{Rows: vortex.Range{End: 4}}, "sorted") {
		if err != nil {
			log.Fatal(err)
		}
		v, err := vortex.Values[int64](b.Col(0))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(b.Len(), v)
	}
}
Output:
4 [1000 1001 1002 1003]
Example (Filter)

Read one column of the rows that meet a filter. The statistics of the file skip the zones that cannot hold a row.

package main

import (
	"context"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	f, err := vortex.OpenFile("testdata/fixtures/0.95.0/extra/default_ints.vortex")
	if err != nil {
		log.Fatal(err)
	}
	defer f.Close()
	q := vortex.Query{Filter: vortex.Col("sorted").Lt(1003), Rows: vortex.Range{End: 10}}
	for b, err := range f.Scan(context.Background(), q, "sorted") {
		if err != nil {
			log.Fatal(err)
		}
		v, err := vortex.Values[int64](b.Col(0))
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(v)
	}
}
Output:
[1000 1001 1002]

func (*File) Schema

func (f *File) Schema() *Schema

Schema returns the schema of the file.

type Kind

type Kind uint8

Kind is the logical type of a column.

const (
	Null Kind = iota
	Bool
	Int8
	Int16
	Int32
	Int64
	Uint8
	Uint16
	Uint32
	Uint64
	Float16
	Float32
	Float64
	KindDecimal
	Utf8
	Binary
	List
	FixedSizeList
	Map
	Struct
	Date
	Time
	Timestamp
	UUID
	Variant
)

The logical types of a Vortex file. Union exists upstream but is in no edition.

func (Kind) String

func (k Kind) String() string

String returns the name of the kind, like "i32" or "fixed_size_list".

type Number

type Number interface {
	~int8 | ~int16 | ~int32 | ~int64 | ~uint8 | ~uint16 | ~uint32 | ~uint64 | ~float32 | ~float64
}

Number is the set of the Go types a numeric column can be read as.

type Query

type Query struct {
	// Filter is exact: a row is returned when it is true, and the caller never has to filter
	// again. The statistics of the file are used to skip what it rules out.
	Filter Expr
	// Rows limits the scan to a range of rows.
	Rows Range
}

Query selects the rows of a scan: the rows of Rows for which Filter is true. The zero value selects every row.

type Range

type Range struct{ Start, End int64 }

Range is a half-open range of rows of a file: Start is the first row, End the one after the last. The zero value is the whole file, so an End of 0 means the end of the file. A range outside the file is clamped to it.

type Ref

type Ref struct {
	// contains filtered or unexported fields
}

Ref is a column, or a field of a struct column, to compare.

func Col

func Col(path ...string) Ref

Col is the column called path[0], or its field path[1], and so on for nested structs.

func (Ref) Eq

func (r Ref) Eq(v any) Expr

Eq is true for the rows whose value equals v.

func (Ref) Ge

func (r Ref) Ge(v any) Expr

Ge is true for the rows whose value is at least v.

func (Ref) Gt

func (r Ref) Gt(v any) Expr

Gt is true for the rows whose value is greater than v.

func (Ref) In

func (r Ref) In(vs ...any) Expr

In is true for the rows whose value equals one of vs.

func (Ref) IsNull

func (r Ref) IsNull() Expr

IsNull is true for the rows that are null, and false for the others.

func (Ref) Le

func (r Ref) Le(v any) Expr

Le is true for the rows whose value is at most v.

func (Ref) Lt

func (r Ref) Lt(v any) Expr

Lt is true for the rows whose value is less than v.

func (Ref) Ne

func (r Ref) Ne(v any) Expr

Ne is true for the rows whose non-null value differs from v.

type RowWriter

type RowWriter[T any] struct {
	// contains filtered or unexported fields
}

RowWriter writes rows, values of the struct type T, to a Vortex file. It is the other half of Rows: the schema comes from the fields of T, with the same tags, and the Go types are the ones that Rows reads. It drives a Writer, which sets the chunks, the statistics and the encodings.

A field is the column named by its tag, vortex:"name", else its own name. The tag vortex:"-" skips the field, unexported fields are skipped and embedded structs are flattened. The Vortex type of a field follows from its Go type:

  • bool, the numbers (int and uint are 64 bits), string (utf8), []byte (binary), [16]byte (uuid) and vortex.Decimal (a decimal, with the tag option decimal(p,s), for precision p and scale s, which int64 takes as well, p up to 18);
  • time.Time is a timestamp in microseconds, UTC, with no zone in the type; the options timestamp(unit) and timestamp(unit,zone) pick another unit (s, ms, us or ns) and a zone name, and date a date in days;
  • time.Duration is a time of day in nanoseconds; the option time(unit) picks another unit;
  • any is a Variant, nullable: nil is a null row, and the other values are the ones that OfVariants takes (see Column.Variant for what Rows gives back);
  • sql.Null[X] and *X are nullable, anything else is not;
  • a struct is a struct, []X a list, [N]X a fixed-size list and map[K]V a map, whose keys are not nullable and whose order of entries is the one of Go's iteration. The options of a list field apply to its elements.

A T that cannot be written is the error of the first Write, and of Close if Write was never called: it names the field and its Go type.

A Write call copies what it needs, so the caller can reuse the rows as soon as it returns. A field that is a number, a bool, a decimal, a time, a uuid, a string or a []byte, plain or in sql.Null, is read without allocating. Pointers, structs, slices and maps allocate.

Write and Close are not safe for concurrent use.

func NewRowWriter

func NewRowWriter[T any](w io.Writer, o WriteOptions) *RowWriter[T]

NewRowWriter returns a RowWriter that writes to w. It does not close w.

Example

Write a slice of structs to a file. The columns come from the fields, and the tags are the ones of Rows.

package main

import (
	"fmt"
	"log"
	"os"
	"time"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	type Trade struct {
		ID     int64     `vortex:"id"`
		Symbol string    `vortex:"symbol"`
		Price  float64   `vortex:"price"`
		At     time.Time `vortex:"at"`
	}
	f, err := os.CreateTemp("", "trades-*.vortex")
	if err != nil {
		log.Fatal(err)
	}
	defer os.Remove(f.Name())
	w := vortex.NewRowWriter[Trade](f, vortex.WriteOptions{})
	n, err := w.Write([]Trade{
		{1, "ACME", 10.5, time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)},
		{2, "ACME", 10.75, time.Date(2026, 1, 2, 3, 4, 6, 0, time.UTC)},
	})
	if err != nil {
		log.Fatal(err)
	}
	if err := w.Close(); err != nil {
		log.Fatal(err)
	}
	if err := f.Close(); err != nil {
		log.Fatal(err)
	}
	fmt.Println(n, "rows written")
}
Output:
2 rows written
Example (ReadBack)

Write rows, then read them back with Rows. A nullable field is a sql.Null or a pointer, and the tag picks the logical type of a decimal.

package main

import (
	"bytes"
	"context"
	"database/sql"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	type Row struct {
		Name  string           `vortex:"name"`
		Price vortex.Decimal   `vortex:"price,decimal(10,2)"`
		Note  sql.Null[string] `vortex:"note"`
		Tags  []string         `vortex:"tags"`
	}
	var buf bytes.Buffer
	w := vortex.NewRowWriter[Row](&buf, vortex.WriteOptions{})
	if _, err := w.Write([]Row{
		{"a", vortex.DecimalFromInt64(1050), sql.Null[string]{V: "first", Valid: true}, []string{"x", "y"}},
		{"b", vortex.DecimalFromInt64(299), sql.Null[string]{}, nil},
	}); err != nil {
		log.Fatal(err)
	}
	if err := w.Close(); err != nil {
		log.Fatal(err)
	}
	f, err := vortex.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		log.Fatal(err)
	}
	for r, err := range vortex.Rows[Row](context.Background(), f, vortex.Query{}) {
		if err != nil {
			log.Fatal(err)
		}
		fmt.Println(r.Name, r.Price.Text(2), r.Note.Valid, r.Tags)
	}
}
Output:
a 10.50 true [x y]
b 2.99 false []

func (*RowWriter[T]) Close

func (w *RowWriter[T]) Close() error

Close writes the footer. A second Close returns nil, and Close does not close the io.Writer.

func (*RowWriter[T]) SetMetadata added in v0.2.0

func (w *RowWriter[T]) SetMetadata(key string, value []byte) error

SetMetadata adds an entry to the metadata of the file, or replaces the value of its key, as Writer.SetMetadata does. It returns the error of NewRowWriter, if any.

func (*RowWriter[T]) Write

func (w *RowWriter[T]) Write(rows []T) (int, error)

Write adds rows to the file. It returns the number of rows it took, which is less than len(rows) when it returns an error. An error closes the writer for writing, and every later call returns it.

type Schema

type Schema struct {
	// contains filtered or unexported fields
}

Schema is the schema of a file: the fields of its root struct.

func NewSchema

func NewSchema(fields ...Field) *Schema

NewSchema returns the schema with these fields, in this order: the root struct of a file. The fields are copied. A schema is checked by NewWriter, which reports a bad one with the error of its first Write.

func (*Schema) Field

func (s *Schema) Field(name string) (Field, bool)

Field returns the first field with this name.

func (*Schema) Fields

func (s *Schema) Fields() []Field

Fields returns a copy of the fields, in file order.

func (*Schema) String

func (s *Schema) String() string

String returns the root struct, like Type.String.

type Type

type Type struct {
	// contains filtered or unexported fields
}

Type is a logical type. It is a value: compare two of them with Equal, not with ==. An accessor that does not apply to the kind of the type returns the zero value.

func BinaryType

func BinaryType() Type

BinaryType is the type of byte strings.

func BoolType

func BoolType() Type

BoolType is the type of booleans.

func DateType

func DateType(unit Unit) Type

DateType is the type of dates: a count of Day or Millisecond since 1970-01-01.

func DecimalOf

func DecimalOf(precision, scale int) Type

DecimalOf is the decimal type of the given precision (1 to 76 digits) and scale (at most the precision).

func FixedSizeListOf

func FixedSizeListOf(elem Type, n int) Type

FixedSizeListOf is the type of lists of exactly n elem.

func Float16Type

func Float16Type() Type

Float16Type is the type of half floats. Its values are written as their 16 bits, with Of[uint16].

func Float32Type

func Float32Type() Type

Float32Type is the type of 32-bit floats.

func Float64Type

func Float64Type() Type

Float64Type is the type of 64-bit floats.

func Int8Type

func Int8Type() Type

Int8Type is the type of 8-bit signed integers.

func Int16Type

func Int16Type() Type

Int16Type is the type of 16-bit signed integers.

func Int32Type

func Int32Type() Type

Int32Type is the type of 32-bit signed integers.

func Int64Type

func Int64Type() Type

Int64Type is the type of 64-bit signed integers.

func ListOf

func ListOf(elem Type) Type

ListOf is the type of variable-length lists of elem.

func MapOf

func MapOf(key, value Type) Type

MapOf is the type of maps from key to value. A key is not nullable.

func NullType

func NullType() Type

NullType is the type whose values are all null. It is always nullable.

func StructOf

func StructOf(fields ...Field) Type

StructOf is the type of structs with these fields. The fields are copied.

func TimeType

func TimeType(unit Unit) Type

TimeType is the type of times of day: a count of Second, Millisecond, Microsecond or Nanosecond since midnight.

func TimestampType

func TimestampType(unit Unit, zone string) Type

TimestampType is the type of instants: a count of unit since 1970-01-01T00:00:00Z. The zone is a name like "UTC", empty for none.

func UUIDType

func UUIDType() Type

UUIDType is the type of 16-byte identifiers.

func Uint8Type

func Uint8Type() Type

Uint8Type is the type of 8-bit unsigned integers.

func Uint16Type

func Uint16Type() Type

Uint16Type is the type of 16-bit unsigned integers.

func Uint32Type

func Uint32Type() Type

Uint32Type is the type of 32-bit unsigned integers.

func Uint64Type

func Uint64Type() Type

Uint64Type is the type of 64-bit unsigned integers.

func Utf8Type

func Utf8Type() Type

Utf8Type is the type of UTF-8 strings.

func VariantType

func VariantType() Type

VariantType is the type of Variant values: any tree of nulls, bools, numbers, strings, binary, times, decimals, arrays and objects, in the Parquet Variant encoding. Its Data is OfVariants.

func (Type) AsNullable

func (t Type) AsNullable() Type

AsNullable returns the type, nullable.

func (Type) Elem

func (t Type) Elem() Type

Elem is the element type of a list or a fixed-size list.

func (Type) Equal

func (t Type) Equal(o Type) bool

Equal reports whether the two types are the same, nullability included.

func (Type) Fields

func (t Type) Fields() []Field

Fields returns a copy of the fields of a struct.

func (Type) Key

func (t Type) Key() Type

Key is the key type of a map.

func (Type) Kind

func (t Type) Kind() Kind

Kind returns the logical type.

func (Type) Nullable

func (t Type) Nullable() bool

Nullable reports whether the values may be null. It is always true for Null.

func (Type) Precision

func (t Type) Precision() int

Precision is the number of digits of a decimal.

func (Type) Scale

func (t Type) Scale() int

Scale is the number of digits of a decimal after the point. It can be negative.

func (Type) Size

func (t Type) Size() int

Size is the number of elements of every value of a fixed-size list.

func (Type) String

func (t Type) String() string

String returns the type in a short form: "i32", "utf8?" (nullable), "decimal(10,2)", "list<i32>", "map<utf8, i64>", "timestamp[ms, tz=UTC]", "struct{a: i32, b: utf8?}".

func (Type) Unit

func (t Type) Unit() Unit

Unit is the time unit of a date, a time or a timestamp.

func (Type) Value

func (t Type) Value() Type

Value is the value type of a map.

func (Type) Zone

func (t Type) Zone() string

Zone is the time zone of a timestamp, empty when it has none.

type Unit

type Unit uint8

Unit is the time unit of a date, a time or a timestamp.

const (
	Nanosecond Unit = iota
	Microsecond
	Millisecond
	Second
	Day
)

The time units, with the values of the file format.

func (Unit) String

func (u Unit) String() string

String returns "ns", "us", "ms", "s" or "days".

type VariantDecimal

type VariantDecimal struct {
	Value Decimal
	Scale int
}

VariantDecimal is a decimal inside a Variant value. A Variant carries the scale of each decimal, which Decimal does not: the value is Value divided by 10 to the power Scale.

func (VariantDecimal) String

func (d VariantDecimal) String() string

String prints the decimal, like Decimal.Text with the scale of the value.

type WriteOptions

type WriteOptions struct {
	// Metadata is the user metadata of the file: values the reader gets back by their key
	// (File.Metadata), that are not rows, a version or an index say. The writer copies the map
	// and stores each value as it is, in the order of the keys. Writer.SetMetadata adds the
	// entries known once the rows are written. A key is a non-empty UTF-8 string of at most
	// MaxMetadataKeyBytes bytes, and a file holds at most MaxMetadataEntries entries: more,
	// as the reference writer and reader refuse, is an error of the first Write or Close.
	// The readers before Vortex 0.87 ignore it, whatever the Edition.
	Metadata map[string][]byte
	// Edition is the edition the file must be readable with, as the upstream names it
	// ("core 2025.05.0"). Empty is the newest the library knows, "core 2026.08.3". The writer
	// only makes what the edition has: a file for an edition before "core 2026.08.0" has the
	// older zone maps (vortex.stats) and only the legacy file statistics, one before
	// "core 2025.10.0" has no listview and no run-length or masked arrays, and so on. An
	// unknown edition, or a type it cannot hold (a uuid before "core 2026.08.3", a map before
	// "core 2026.08.2", a fixed-size list before "core 2025.10.0"), is an error of the first
	// Write or Close.
	Edition string
	// Buffer is the bytes of rows, as they are before compression, that may wait to be
	// compressed together: the writer compresses the chunks that wait on every core, and each
	// one holds its rows and the memory of its compressor until it is written. 0 is the
	// default, a queue of chunks whose length depends on the schema (two chunks of about 1 MiB
	// a column, 16 at least). A smaller Buffer lowers the memory of the writer and uses fewer
	// cores at once; under the size of a chunk, the chunks are compressed one at a time, on one
	// core. A larger one only matters for a file of few columns. The rows of the file do not
	// depend on it, the order of its segments may.
	Buffer      int
	Compression Compression
}

WriteOptions are the options of a Writer.

Example (Edition)

Write a file that Vortex 0.83 and older can open: the edition is the oldest one.

package main

import (
	"bytes"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	s := vortex.NewSchema(vortex.Field{Name: "id", Type: vortex.Int64Type()})
	var buf bytes.Buffer
	w := vortex.NewWriter(&buf, s, vortex.WriteOptions{Edition: "core 2025.05.0"})
	if err := w.Write(vortex.Of([]int64{1, 2, 3})); err != nil {
		log.Fatal(err)
	}
	if err := w.Close(); err != nil {
		log.Fatal(err)
	}
	f, err := vortex.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(f.NumRows(), f.Schema())

	// A type the edition does not have is an error.
	u := vortex.NewSchema(vortex.Field{Name: "id", Type: vortex.UUIDType()})
	err = vortex.NewWriter(&buf, u, vortex.WriteOptions{Edition: "core 2025.05.0"}).Close()
	fmt.Println(err)
}
Output:
3 struct{id: i64}
vortex: NewWriter: field "id": a uuid is not in the edition "core 2025.05.0" (dtype vortex.uuid is newer)

type Writer

type Writer struct {
	// contains filtered or unexported fields
}

Writer writes a Vortex file. It needs an io.Writer and never seeks.

A column takes the Data its type calls for: Of for the numbers (the Go type is the one of the column, int32 for Int32; the storage of a date, a time or a timestamp, and uint16 for the bits of a Float16), OfBools, OfStrings or OfBytes for Utf8 and Binary, OfBytes for a UUID, OfDecimals, OfVariants for a Variant, OfNulls, OfStruct, and OfList for a list, a fixed-size list and a map. Each Write adds rows. The rows of a column are cut into chunks that do not depend on how the caller splits them: at multiples of 8,192 rows, about 1 MiB of data a chunk. Each column carries the statistics a reader uses to skip a zone, and a column of few distinct values is written as a dictionary. Write copies the rows into a buffer of a few MiB a column, so they reach the io.Writer when a chunk is full, and at Close.

Write and Close are not safe for concurrent use.

func NewWriter

func NewWriter(w io.Writer, s *Schema, o WriteOptions) *Writer

NewWriter returns a Writer of a file with this schema. Nothing is written until the first Write or Close. A schema that cannot be written (a decimal of precision 0, say) is reported by the first Write or Close.

Example

Write columns: a schema, then one Write per chunk with a Data per column.

package main

import (
	"bytes"
	"fmt"
	"log"

	vortex "github.com/fclairamb/vortex-go"
)

func main() {
	s := vortex.NewSchema(
		vortex.Field{Name: "id", Type: vortex.Int64Type()},
		vortex.Field{Name: "name", Type: vortex.Utf8Type()},
	)
	var buf bytes.Buffer
	w := vortex.NewWriter(&buf, s, vortex.WriteOptions{})
	if err := w.Write(vortex.Of([]int64{1, 2, 3}), vortex.OfStrings([]string{"a", "b", "c"})); err != nil {
		log.Fatal(err)
	}
	if err := w.Close(); err != nil {
		log.Fatal(err)
	}
	f, err := vortex.Open(bytes.NewReader(buf.Bytes()), int64(buf.Len()))
	if err != nil {
		log.Fatal(err)
	}
	fmt.Println(f.NumRows(), f.Schema())
}
Output:
3 struct{id: i64, name: utf8}

func (*Writer) Close

func (w *Writer) Close() error

Close writes the footer. The writer is closed for writing, and w is left open. A file with no row has one empty chunk. A second Close returns nil; Close returns the error that closed the writer for writing, if any.

func (*Writer) SetMetadata added in v0.2.0

func (w *Writer) SetMetadata(key string, value []byte) error

SetMetadata adds an entry to the metadata of the file, or replaces the value of its key: the way to store what is only known once the rows are written. The writer keeps a copy of value and writes it at Close. A key is a non-empty UTF-8 string of at most MaxMetadataKeyBytes bytes, and a file holds at most MaxMetadataEntries entries: SetMetadata returns an error for an entry beyond these, and the writer goes on without it. After Close it returns ErrWriterClosed.

func (*Writer) Write

func (w *Writer) Write(cols ...Data) error

Write adds rows to the file: one Data per field of the schema, all of the same length. It returns an error when a Data does not fit its field, and then, or when the io.Writer fails, the writer is closed for writing. Write keeps none of the slices of the Data: the caller may write them again when it returns. It copies the bytes of OfBytes, not the ones of the strings of OfStrings, which a Go string never changes: it points to them until their chunk is written. The rows are in the io.Writer when Close returns, some of them before.

Directories

Path Synopsis
internal
array
Package array decodes the serialized arrays of a flat segment into in-memory arrays.
Package array decodes the serialized arrays of a flat segment into in-memory arrays.
compress
Package compress is the compressor of the writer: for one chunk of one column, it tries the encodings of internal/encode that fit its type on a sample of the rows, keeps the one that makes the smallest array, and applies it to the whole chunk.
Package compress is the compressor of the writer: for one chunk of one column, it tries the encodings of internal/encode that fit its type on a sample of the rows, keeps the one that makes the smallest array, and applies it to the whole chunk.
edition
Package edition holds the members of the newest core edition the pinned upstream release supports.
Package edition holds the members of the newest core edition the pinned upstream release supports.
encode
Package encode is the encoders of the lightweight encodings: bit-packing, frame of reference, zigzag, run-length, run-end, dictionary, sequence, constant and sparse.
Package encode is the encoders of the lightweight encodings: bit-packing, frame of reference, zigzag, run-length, run-end, dictionary, sequence, constant and sparse.
fbs
Package fbs holds typed accessors over flatbuf.Table for the tables of the four flatbuffers schemas a Vortex file uses.
Package fbs holds typed accessors over flatbuf.Table for the tables of the four flatbuffers schemas a Vortex file uses.
flatbuf
Package flatbuf reads flatbuffers, by hand, from untrusted bytes, and builds them (Builder).
Package flatbuf reads flatbuffers, by hand, from untrusted bytes, and builds them (Builder).
flatbuf/fbtest
Package fbtest builds flatbuffers for tests.
Package fbtest builds flatbuffers for tests.
gen
Package gen writes the files that are generated from the code: the example and the support matrix of README.md, the code blocks and the support matrix of the pages of website/, and api.txt.
Package gen writes the files that are generated from the code: the example and the support matrix of README.md, the code blocks and the support matrix of the pages of website/, and api.txt.
pco
Package pco decodes the wrapped format of Pco, the numeric codec behind vortex.pco.
Package pco decodes the wrapped format of Pco, the numeric codec behind vortex.pco.
protowire
Package protowire decodes the protobuf wire format, by hand: varints, zigzag, fixed32, fixed64, length-delimited fields and packed repeated scalars.
Package protowire decodes the protobuf wire format, by hand: varints, zigzag, fixed32, fixed64, length-delimited fields and packed repeated scalars.
scalar
Package scalar decodes a protobuf-serialized vortex.scalar.ScalarValue into a small Go value.
Package scalar decodes a protobuf-serialized vortex.scalar.ScalarValue into a small Go value.
testutil
Package testutil holds test-only helpers.
Package testutil holds test-only helpers.
unsafex
Package unsafex is the only package of the module that imports unsafe.
Package unsafex is the only package of the module that imports unsafe.
variant
Package variant decodes the values of the Parquet Variant encoding (apache/parquet-format, VariantEncoding.md): a metadata dictionary of the object keys and a value, both byte strings.
Package variant decodes the values of the Parquet Variant encoding (apache/parquet-format, VariantEncoding.md): a metadata dictionary of the object keys and a value, both byte strings.

Jump to

Keyboard shortcuts

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