csvfmt

package
v0.12.0 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 24 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 csvfmt defines the CSV export format: the group-level column layout derived from schema protos, the cell value encoding with its `\N` and `\B` sentinels, and a rolling writer that splits one CSV stream into size-bounded files. A layout's columns follow resources in name order, so it does not depend on the order schemas are listed.

The package must not import anything under banyand/ so that the data node, the client and the importer share exactly the same pure functions.

Index

Constants

View Source
const NullCell = `\N`

NullCell is the sentinel cell of a null value.

View Source
const SinkWriteSize = 256 << 10

SinkWriteSize is the maximum length of one Sink.Write call; on-disk bytes are buffered up to this size before being handed to the sink.

View Source
const TopNResultMeasure = topnschema.Name

TopNResultMeasure is the internal measure that stores pre-aggregated Top-N results. It is exported like any other measure; its binary field carries an engine-internal encoding.

Variables

This section is empty.

Functions

func DecodeCell

func DecodeCell(cell string, t ValueType) (value any, isNull bool, err error)

DecodeCell is the inverse of the Encode functions. The value is a string, int64 (int and timestamp), float64, []byte, []string or []int64 depending on t; isNull reports NullCell.

func DecodeElementID

func DecodeElementID(cell string) (uint64, error)

DecodeElementID parses a cell written by EncodeElementID back into the element id.

func EncodeBinary

func EncodeBinary(b []byte) string

EncodeBinary encodes a binary cell with standard padded base64, matching protojson. An empty slice encodes to "" which stays distinct from NullCell.

func EncodeElementID

func EncodeElementID(id uint64) string

EncodeElementID encodes a stream element id as the 16 lowercase hex digits of its big-endian bytes, the form a stream query returns as element_id.

func EncodeFieldValue

func EncodeFieldValue(v *modelv1.FieldValue) string

EncodeFieldValue encodes a field value according to its oneof; nil and null become NullCell.

func EncodeFloat

func EncodeFloat(v float64) string

EncodeFloat encodes a float cell with the shortest exact 'f' representation; NaN and infinities become "NaN", "+Inf" and "-Inf".

func EncodeInt

func EncodeInt(v int64) string

EncodeInt encodes an int cell in decimal.

func EncodeIntArray

func EncodeIntArray(v []int64) string

EncodeIntArray encodes an int array as ';'-joined decimals; an empty array is "".

func EncodeString

func EncodeString(s string) string

EncodeString encodes a string cell. A value containing '\r' is downgraded to `\B`+base64 because encoding/csv rewrites "\r\n" to "\n" on read; otherwise a value starting with a backslash gets one extra leading backslash so that it never collides with the `\N` and `\B` sentinels.

func EncodeStringArray

func EncodeStringArray(v []string) string

EncodeStringArray encodes a string array as a JSON array. A nil slice encodes as "[]". Invalid UTF-8 bytes are replaced with U+FFFD by encoding/json.

func EncodeTagValue

func EncodeTagValue(v *modelv1.TagValue) string

EncodeTagValue encodes a tag value according to its oneof; nil and null become NullCell.

func EncodeTimestamp

func EncodeTimestamp(unixNano int64) string

EncodeTimestamp encodes a time column as int64 UnixNano decimal.

func FitsColumn

func FitsColumn(v *modelv1.TagValue, t ValueType) bool

FitsColumn reports whether EncodeTagValue writes v losslessly into a column of type t: a null value fits every column, any other value only a column of its own type, and a timestamp only within the int64 nanosecond range.

func RowSize

func RowSize(msg proto.Message) int

RowSize returns the bytes msg adds to a batch as an element of a repeated field, apart from the field tag: its length prefix plus its encoded size.

Types

type Column

type Column struct {
	// Header is the human-readable header cell, e.g. "_name", "searchable.trace_id",
	// "_field.value" or "svc_a::default.foo" for a type-conflict split column.
	Header string
	// Family is the tag family of a stream/measure tag column; empty otherwise.
	Family string
	// Name is the tag or field name; empty for fixed columns.
	Name string
	// Resources lists the resources owning a tag/field column; nil for fixed columns.
	Resources []string
	Kind      ColumnKind
	Type      ValueType
}

Column describes one CSV column.

type ColumnKind

type ColumnKind uint8

ColumnKind tells where the value of a column comes from.

const (
	KindName ColumnKind = iota
	KindElementID
	KindTimestamp
	KindVersion
	KindTraceID
	KindSpanID
	KindSpan
	KindPropertyID
	KindModRevision
	KindCreateRevision
	KindUpdatedAt
	KindDeleteTime
	KindTag
	KindField
)

Column kinds. The fixed columns of each model come first in a layout, followed by KindTag columns and, for measures, KindField columns.

type Layout

type Layout struct {
	Columns []Column
	// contains filtered or unexported fields
}

Layout is the group-level column vector of a CSV stream. It is a pure function of the schemas it was built from: columns follow resources in name order, so the same schemas in any order always produce the same layout.

func MeasureLayout

func MeasureLayout(measures []*databasev1.Measure) (*Layout, error)

MeasureLayout builds the layout of a measure group: _name, _timestamp, _version, then the union of family.tag columns and the union of _field.* columns. Index-mode measures have no fields and so contribute no field columns. Columns follow resources in name order, whatever the order of measures.

func PropertyLayout

func PropertyLayout(props []*databasev1.Property) (*Layout, error)

PropertyLayout builds the layout of a property group: _name, _id, _mod_revision, _create_revision, _updated_at, _delete_time, then the union of tag columns. Columns follow resources in name order, whatever the order of props.

func StreamLayout

func StreamLayout(streams []*databasev1.Stream) (*Layout, error)

StreamLayout builds the layout of a stream group: _name, _element_id, _timestamp, then the union of family.tag columns. Columns follow resources in name order, whatever the order of streams.

func TraceLayout

func TraceLayout(traces []*databasev1.Trace) (*Layout, error)

TraceLayout builds the layout of a trace group: _name, trace_id, span_id, _span, then the union of tag columns, excluding each trace's own trace-id and span-id tags. Columns follow resources in name order, whatever the order of traces.

func (*Layout) CheckRow

func (l *Layout) CheckRow(row []Value) error

CheckRow verifies that the row's resource (column 0) is in the layout and that every tag or field column the resource does not own is null.

func (*Layout) DatatypeLine

func (l *Layout) DatatypeLine() []string

DatatypeLine returns the optional annotation row: "#datatype" followed by one type token per column, so its length is len(Columns)+1. Readers of annotated files must therefore allow a variable number of fields per record.

func (*Layout) FieldIndex

func (l *Layout) FieldIndex(resource, field string) (int, bool)

FieldIndex returns the column index of a measure's field.

func (*Layout) Header

func (l *Layout) Header() []string

Header returns the header row.

func (*Layout) NewRow

func (l *Layout) NewRow() []string

NewRow returns a row with every cell set to NullCell.

func (*Layout) TagIndex

func (l *Layout) TagIndex(resource, family, tag string) (int, bool)

TagIndex returns the column index of a resource's tag. family is "" for trace and property.

type Reader

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

Reader reads the records of one CSV file written by Writer for a layout. It checks the header, and the optional #datatype line before it, against the layout. A Reader is not safe for concurrent use.

func NewReader

func NewReader(r io.Reader, layout *Layout, opts ReaderOptions) (*Reader, error)

NewReader reads and validates the prelude of a CSV file: an optional #datatype line, whose tokens must match the column types, followed by the header, whose cells must equal Layout.Header().

func (*Reader) Close

func (r *Reader) Close() error

Close releases the reader; Next fails afterwards. It does not close the underlying io.Reader. Read errors are reported by Next, never by Close.

func (*Reader) Next

func (r *Reader) Next() ([]Value, error)

Next returns the next record, or io.EOF after the last one. The returned slice and its Values are overwritten by the next call, but the slices and strings the Values hold are never reused. Errors carry the record number and are sticky.

func (*Reader) RecordNo

func (r *Reader) RecordNo() uint64

RecordNo returns the 1-based number of the last data record returned by Next; records are counted, not physical lines, and the prelude is not counted.

type ReaderOptions

type ReaderOptions struct {
	// Gzip tells that the input is gzip-compressed.
	Gzip bool
}

ReaderOptions configures NewReader.

type Sink

type Sink interface {
	// StartFile announces a new file; seq starts at 1 and has no gaps.
	StartFile(relativePath string, seq uint32) error
	// Write receives bytes exactly as they land on disk (after gzip), at most SinkWriteSize
	// bytes per call. p is reused after Write returns and must not be retained.
	Write(p []byte) error
	// FinishFile seals the current file. size and crc (IEEE CRC-32) cover every byte passed
	// to Write for this file; rowCounts holds the per-resource row count of the file.
	FinishFile(size uint64, crc uint32, rowCounts map[string]uint64) error
}

Sink receives the files produced by a Writer.

type Value

type Value struct {
	Str   string
	Bytes []byte
	Strs  []string
	Ints  []int64
	Int   int64
	Float float64
	Null  bool
}

Value is one decoded cell. Null is set for NullCell; otherwise the field matching the column type is set: Str, Int (int and timestamp columns), Float, Bytes, Strs or Ints. An empty binary cell decodes to a non-nil empty Bytes and an empty int array to a non-nil empty Ints, so both stay distinct from null.

func (Value) Encode

func (v Value) Encode(t ValueType) string

Encode renders a cell of a column of type t in its canonical CSV encoding; it is the inverse of decoding. Null and an unknown type yield NullCell.

func (Value) FieldValue

func (v Value) FieldValue(t ValueType) *modelv1.FieldValue

FieldValue converts a cell of a column of type t to a field value. Null and a type a field cannot hold yield the null field value.

func (Value) TagValue

func (v Value) TagValue(t ValueType) *modelv1.TagValue

TagValue converts a cell of a column of type t to a tag value. Null and a type a tag cannot hold (float) yield the null tag value.

type ValueType

type ValueType uint8

ValueType is the cell encoding type of a column.

const (
	ValueString ValueType = iota
	ValueInt
	ValueFloat
	ValueBinary
	ValueStringArray
	ValueIntArray
	ValueTimestamp
)

Value types of CSV columns.

func (ValueType) String

func (t ValueType) String() string

String returns the `#datatype` token of the value type.

type Writer

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

Writer writes one CSV stream, rolling to the next file after a complete row once the on-disk bytes of the current file reach MaxFileSize. Every file repeats the header. A Writer is not safe for concurrent use.

func NewWriter

func NewWriter(sink Sink, opts WriterOptions) *Writer

NewWriter creates a Writer that emits files to sink.

func (*Writer) Close

func (w *Writer) Close() error

Close finishes the open file. No file is produced when no row was ever written.

func (*Writer) Flush

func (w *Writer) Flush() error

Flush hands every byte of the open file written so far to the sink, including what the compressor still holds, so that a reader of the stream sees each row already written. A gzip flush ends the deflate block early, which costs a little compression. Flush does nothing without an open file.

func (*Writer) Oversized

func (w *Writer) Oversized() (rows, largest uint64)

Oversized returns how many rows got a file of their own for being larger than MaxFileSize, and the encoded length of the largest of them.

func (*Writer) Rows

func (w *Writer) Rows() uint64

Rows returns the number of rows written so far.

func (*Writer) WriteRow

func (w *Writer) WriteRow(resource string, cells []string) error

WriteRow writes one row. cells must come from Layout.NewRow; cells[0] is overwritten with resource. Rows are never split across files: the file rolls after a row once its on-disk bytes reach MaxFileSize, and a row whose encoded length alone reaches MaxFileSize is written to a file of its own.

type WriterOptions

type WriterOptions struct {
	Layout *Layout
	// PathPrefix is e.g. "stream/sw_record/seg-20260907/shard-0"; the writer appends
	// "-%05d.csv" or "-%05d.csv.gz".
	PathPrefix string
	// MaxFileSize is the soft on-disk size limit of one file; 0 never rolls.
	MaxFileSize uint64
	Gzip        bool
	// Annotations writes a "#datatype" line before the header of every file.
	Annotations bool
}

WriterOptions configures a Writer.

Jump to

Keyboard shortcuts

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