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 ¶
- Constants
- Variables
- func Rows[T any](ctx context.Context, f *File, q Query) iter.Seq2[T, error]
- func Values[T Number](c *Column) ([]T, error)
- type Batch
- type Column
- func (c *Column) Bool(i int) bool
- func (c *Column) Bytes(i int) []byte
- func (c *Column) Decimal(i int) Decimal
- func (c *Column) Elems() *Column
- func (c *Column) Field(i int) *Column
- func (c *Column) List(i int) (start, end int)
- func (c *Column) Null(i int) bool
- func (c *Column) Type() Type
- func (c *Column) Variant(i int) (any, error)
- func (c *Column) VariantBytes(i int) (metadata, value []byte, err error)
- type Compression
- type Data
- func Of[T Number](v []T) Data
- func OfBools(v []bool) Data
- func OfBytes(v [][]byte) Data
- func OfDecimals(v []Decimal) Data
- func OfList(offsets []int, elems Data) Data
- func OfNulls(n int) Data
- func OfStrings(v []string) Data
- func OfStruct(fields ...Data) Data
- func OfVariantBytes(metadata, value [][]byte) Data
- func OfVariants(vals []any) Data
- type Decimal
- type Expr
- type Field
- type File
- func (f *File) Close() error
- func (f *File) Layout() (*LayoutNode, error)
- func (f *File) Metadata(key string) ([]byte, bool, error)
- func (f *File) MetadataKeys() []string
- func (f *File) NumRows() int64
- func (f *File) Scan(ctx context.Context, q Query, columns ...string) iter.Seq2[*Batch, error]
- func (f *File) Schema() *Schema
- type Kind
- type LayoutNode
- type Number
- type Query
- type Range
- type Ref
- type RowWriter
- type ScanStats
- type Schema
- type Type
- func BinaryType() Type
- func BoolType() Type
- func DateType(unit Unit) Type
- func DecimalOf(precision, scale int) Type
- func FixedSizeListOf(elem Type, n int) Type
- func Float16Type() Type
- func Float32Type() Type
- func Float64Type() Type
- func Int8Type() Type
- func Int16Type() Type
- func Int32Type() Type
- func Int64Type() Type
- func ListOf(elem Type) Type
- func MapOf(key, value Type) Type
- func NullType() Type
- func StructOf(fields ...Field) Type
- func TimeType(unit Unit) Type
- func TimestampType(unit Unit, zone string) Type
- func UUIDType() Type
- func Uint8Type() Type
- func Uint16Type() Type
- func Uint32Type() Type
- func Uint64Type() Type
- func Utf8Type() Type
- func VariantType() Type
- func (t Type) AsNullable() Type
- func (t Type) Elem() Type
- func (t Type) Equal(o Type) bool
- func (t Type) Fields() []Field
- func (t Type) Key() Type
- func (t Type) Kind() Kind
- func (t Type) Nullable() bool
- func (t Type) Precision() int
- func (t Type) Scale() int
- func (t Type) Size() int
- func (t Type) String() string
- func (t Type) Unit() Unit
- func (t Type) Value() Type
- func (t Type) Zone() string
- type Unit
- type VariantDecimal
- type WriteOptions
- type Writer
Examples ¶
Constants ¶
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 ¶
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.
var ErrDecimalRange = errors.New("vortex: decimal out of the range of 256 bits")
ErrDecimalRange reports a value that does not fit in 256 bits.
var ErrWriterClosed = errors.New("vortex: the writer is closed")
ErrWriterClosed is returned by Write after Close.
Functions ¶
func Rows ¶
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.96.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.96.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 ¶
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, or as uint16 for its 16 bits (the float16 of Arrow); int16 is refused. The slice is a view, valid for the iteration, except for the float32 of a f16 column, which is a copy.
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.
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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 ¶
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) Variant ¶
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.
func (*Column) VariantBytes ¶ added in v0.4.0
VariantBytes returns the Parquet Variant encoding of row i of a Variant column: its metadata and its value, both nil for a null row. When the column stores the row unshredded the bytes are a view, valid until the next batch; when it is shredded they are re-encoded, a copy. 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 ¶
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 OfBytes ¶
OfBytes is the values of a binary or utf8 column, and of a uuid column, whose values are 16 bytes each.
func OfDecimals ¶
OfDecimals is the values of a decimal column: the unscaled values.
func OfList ¶
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 OfVariantBytes ¶ added in v0.4.0
OfVariantBytes is the values of a Variant column given in the Parquet Variant encoding: one metadata and one value per row, both nil for a null row. Write checks each pair, the metadata must parse and the value decode against it, and returns an error naming the row otherwise. The bytes are written as they are.
func OfVariants ¶
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.
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 ¶
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 ¶
DecimalFromInt64 returns the decimal whose unscaled value is v.
func DecimalFromWords ¶ added in v0.4.0
DecimalFromWords returns the decimal of the 256 bits w, least significant word first, in two's complement. Every [4]uint64 is a valid number, so it returns no error. A decimal128 whose words are lo and hi is DecimalFromWords([4]uint64{lo, hi, s, s}), with s the sign extension of hi, that is uint64(int64(hi) >> 63). A value outside the precision of its column is an error of Write.
func (Decimal) Cmp ¶
Cmp compares the values: -1 when d is less than o, 0 when equal, +1 when greater.
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.
type File ¶
type File struct {
// contains filtered or unexported fields
}
File is an open Vortex file. It is safe for concurrent use.
func Open ¶
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 OpenMapped ¶
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 ¶
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) Layout ¶ added in v0.3.0
func (f *File) Layout() (*LayoutNode, error)
Layout returns a copy of the layout tree of the file. For a flat layout it reads the end of its segment, the description of the array, and not its data: the error is the one of that read.
func (*File) Metadata ¶ added in v0.2.0
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
MetadataKeys returns the keys of the metadata of the file, sorted. A file holds at most MaxMetadataEntries of them.
func (*File) Scan ¶
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.96.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.96.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]
type Kind ¶
type Kind uint8
Kind is the logical type of a column.
type LayoutNode ¶ added in v0.3.0
type LayoutNode struct {
// ID is the identifier of the layout: "vortex.struct", "vortex.chunked", "vortex.flat",
// "vortex.zoned", "vortex.dict"...
ID string
// Name is what the node is for its parent: the field of a struct layout, "data" or
// "zones" for a zoned layout, "values" or "codes" for a dictionary, "validity" for the
// validity of a nullable struct. It is empty for the root and the chunks of a chunked
// layout.
Name string
// Encoding is the identifier of the encoding of the root array of a flat layout
// ("vortex.bitpacked", "vortex.fsst"...), and is empty for another one.
Encoding string
// Children are the nodes below, in the order of the file.
Children []*LayoutNode
// Rows is the number of rows of the node.
Rows int64
// Offset and Bytes locate the segment of a flat layout, and are 0 for another one.
Offset, Bytes int64
}
LayoutNode describes a node of the layout tree of a file: how its rows are stored. It is a copy, read-only for the caller.
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
// Stats, when not nil, is set by the scan to what it did: it is reset when the scan starts
// and complete when the scan ends. It is not safe to read it while the scan runs.
Stats *ScanStats
// 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.
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 ¶
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
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.
type ScanStats ¶ added in v0.3.0
type ScanStats struct {
// Chunks is the number of flat segments of the columns the scan reads, in its rows.
Chunks int
// ChunksSkipped is the number of those that the filter ruled out by the zone maps: they
// are not read.
ChunksSkipped int
// RowsRead is the number of rows that were decoded to be filtered or returned. The rows
// of a zone the filter rules out are not counted.
RowsRead int64
// RowsKept is the number of rows returned.
RowsKept int64
}
ScanStats tells what a scan read and what it skipped.
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 ¶
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.
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 DecimalOf ¶
DecimalOf is the decimal type of the given precision (1 to 76 digits) and scale (at most the precision).
func FixedSizeListOf ¶
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 NullType ¶
func NullType() Type
NullType is the type whose values are all null. It is always nullable.
func TimeType ¶
TimeType is the type of times of day: a count of Second, Millisecond, Microsecond or Nanosecond since midnight.
func TimestampType ¶
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 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) 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?}".
type Unit ¶
type Unit uint8
Unit is the time unit of a date, a time or a timestamp.
The time units, with the values of the file format.
type VariantDecimal ¶
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 ¶
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
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 ¶
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.
Source Files
¶
- column.go
- data.go
- decimal.go
- doc.go
- dtype.go
- expr.go
- expr_fast.go
- file.go
- footer.go
- inspect.go
- layout.go
- mapped.go
- mapped_unix.go
- metadata.go
- pipeline.go
- prune.go
- rows.go
- rows_fast.go
- rowwriter.go
- scan.go
- schema.go
- wbuf.go
- wcheck.go
- wcol.go
- wcompress.go
- wdict.go
- wencode.go
- wforce.go
- wfstats.go
- writer.go
- wstats.go
- wstats_fast.go
- wtable.go
- zoned.go
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. |