csv

package
v0.10.1 Latest Latest
Warning

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

Go to latest
Published: Oct 21, 2026 License: Apache-2.0 Imports: 15 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.

README

Typed CSV codec

github.com/viant/structology/encoding/csv owns a fixed CSV codec for new consumers, including Datly v1. The existing SQLX CSV package remains unchanged.

import "github.com/viant/structology/encoding/csv"

type Record struct {
    ID   int    `csvName:"id"`
    Name string `csvName:"name"`
}

encoded, err := csv.Marshal([]Record{{ID: 1, Name: `say "hello", please`}})
var records []Record
err = csv.Unmarshal(encoded, &records)

The default writer doubles embedded quotes, preserves commas, backslashes and newlines inside quoted fields, and writes a header. The reader follows Go's encoding/csv rules, including CRLF normalization. It distinguishes an unquoted null marker from a quoted literal such as "null" when decoding nullable fields. Zero, false and empty strings remain distinct from null.

NewMarshaller(reflect.TypeFor[Record](), config) compiles an immutable typed shape for repeated concurrent Marshal and Unmarshal calls. Constructors copy configuration rather than changing caller-owned settings. The convenience functions cache default shapes. Decode destinations are nonnil pointers to slices; decoding appends records and may retain earlier appends if a later row is invalid.

Supported behavior includes struct/pointer/slice/array roots, scalar aliases, csvName aliases, csvName:"-" exclusions, hidden presence markers, pointer scalars, time values and timeLayout tags. Nested holders flatten into dotted headers. Sibling relation slices retain the SQLX Cartesian-row behavior, including relation-only projections. UniqueFields and References are rejected explicitly: decoding yields one root per CSV record and does not infer identity-based regrouping. Recursive shapes and duplicate headers are rejected.

Empty collections and nil roots produce headers without records. Nil elements in root pointer slices are skipped. Standard delimiters such as comma, semicolon and tab work for both directions. Explicit nonstandard enclosure/escape settings are available for writer compatibility; the decoder requires double-quote escaping. NewReader retains the flat streaming adapter: it requires at least one record and emits headers only when a StringifierConfig is supplied.

CSV quoting is not spreadsheet-formula sanitization. Applications exporting untrusted values for spreadsheets should apply their own cell policy.

Provenance

Typed relation traversal and scalar formatting were ported from Viant SQLX's io/load/reader/csv and supporting generic helpers under the Apache 2.0 license. The new codec has no production import of SQLX. Its formatting helper uses Tagly, consistent with Structology. Changes here do not modify the SQLX implementation.

Checks

go test -race ./encoding/csv/...
go test ./encoding/csv -run '^$' -bench BenchmarkMarshal1000 -benchmem
go test ./encoding/csv -run '^$' -fuzz FuzzCSVStrings -fuzztime 5s

Documentation

Overview

Package csv provides typed CSV encoding and decoding. Its default dialect uses standard double-quote escaping and preserves literal commas and backslashes. The initial typed relation traversal was ported from SQLX; SQLX remains unchanged.

Index

Constants

View Source
const (
	TagName = "csvName"
)

Variables

This section is empty.

Functions

func Elem

func Elem(rType reflect.Type) reflect.Type

func EscapeSpecialChars

func EscapeSpecialChars(value string, config *Config) string

func Marshal

func Marshal(value any) ([]byte, error)

Marshal encodes a struct, pointer, array or slice with a header row. Compiled default shapes are cached and can be reused concurrently.

func Unmarshal

func Unmarshal(data []byte, destination any) error

Unmarshal appends decoded records to a nonnil pointer to a typed slice.

func WriteObject

func WriteObject(writer *Buffer, config *Config, values []string, wasString []bool)

Types

type Accessor

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

func (*Accessor) Has

func (a *Accessor) Has() bool

func (*Accessor) Headers

func (a *Accessor) Headers() []string

func (*Accessor) Interfacer

func (a *Accessor) Interfacer() *xunsafe.Type

func (*Accessor) Reset

func (a *Accessor) Reset()

func (*Accessor) Set

func (a *Accessor) Set(pointer unsafe.Pointer)

func (*Accessor) Stringify

func (a *Accessor) Stringify(writer *writer)

type Buffer

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

Buffer represents itemBuffer

func NewBuffer

func NewBuffer(size int) *Buffer

NewBuffer creates a itemBuffer instance with given initial size

func (*Buffer) Read

func (b *Buffer) Read(dest []byte) (int, error)

Read reads current item itemBuffer to dest

type Config

type Config struct {
	FieldSeparator  string
	ObjectSeparator string
	EncloseBy       string
	EscapeBy        string
	// RawNullValue emits the null marker as an already encoded wire token.
	// Literal strings equal to the marker remain enclosed and escaped.
	RawNullValue      bool
	NullValue         string
	Stringify         StringifyConfig
	UniqueFields      []string
	References        []*Reference // parent -> children. Foo.ID -> Boo.FooId
	ExcludedPaths     []string
	StringifierConfig io.StringifierConfig
}

Config represents reader config

type Field

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

type Index

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

func (*Index) Get

func (i *Index) Get(key string) (interface{}, bool)

func (*Index) Has

func (i *Index) Has(owner, value interface{}) bool

type Marshaller

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

func NewMarshaller

func NewMarshaller(rType reflect.Type, config *Config) (*Marshaller, error)

func (*Marshaller) Marshal

func (m *Marshaller) Marshal(val interface{}, options ...interface{}) ([]byte, error)

func (*Marshaller) ReadHeaders

func (m *Marshaller) ReadHeaders(b []byte) ([]string, error)

func (*Marshaller) Unmarshal

func (m *Marshaller) Unmarshal(b []byte, dest interface{}) error

type Node

type Node interface {
	ID() interface{}
	ParentID() interface{}
	AddChildren(node Node)
}

func BuildTree

func BuildTree(nodes []Node) []Node

type NodeIndex

type NodeIndex map[interface{}]map[interface{}]bool

func (NodeIndex) Get

func (i NodeIndex) Get(id interface{}) map[interface{}]bool

type Object

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

func ParentOf

func ParentOf(objects []*Object) (*Object, bool)

func (*Object) Accessor

func (o *Object) Accessor(accessorIndex int, mainConfig *Config, depth int, configs []*Config) (*Accessor, error)

func (*Object) AddChildren

func (o *Object) AddChildren(node Node)

func (*Object) AddHolder

func (o *Object) AddHolder(field *Field, holder *string, nullValue *bool)

func (*Object) CheckIndexed

func (o *Object) CheckIndexed() (interface{}, bool)

func (*Object) Has

func (o *Object) Has(parent interface{}, value interface{}) bool

func (*Object) ID

func (o *Object) ID() interface{}

func (*Object) ParentID

func (o *Object) ParentID() interface{}

func (*Object) Umarshal

func (o *Object) Umarshal() error

type ObjectIndex

type ObjectIndex map[interface{}]PresenceIndex

func (ObjectIndex) Index

func (i ObjectIndex) Index(value interface{}) PresenceIndex

type PresenceIndex

type PresenceIndex map[interface{}]bool

func (PresenceIndex) Has

func (p PresenceIndex) Has(value interface{}) bool

type Reader

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

Reader represents plain text reader

func NewReader

func NewReader(any interface{}, config *Config, options ...interface{}) (*Reader, reflect.Type, error)

NewReader returns Reader instance and actual data struct type. e.g. data is type of []*Foo - returns Foo.

func (*Reader) ItemCount

func (r *Reader) ItemCount() int

ItemCount returns count of items inside itemBuffer

func (*Reader) Read

func (r *Reader) Read(buffer []byte) (n int, err error)

Read data into itemBuffer

type Reference

type Reference struct {
	ParentField string
	ChildField  string
}

type StringifierConfig

type StringifierConfig = scalar.StringifierConfig

StringifierConfig retains the ported numeric/field formatting options without exposing a dependency on SQLX.

type StringifierFloat32Config

type StringifierFloat32Config = scalar.StringifierFloat32Config

type StringifierFloat64Config

type StringifierFloat64Config = scalar.StringifierFloat64Config

type StringifyConfig

type StringifyConfig struct {
	IgnoreFieldSeparator  bool
	IgnoreObjectSeparator bool
	IgnoreEncloseBy       bool
}

StringifyConfig "extends" Config with ignore flags

type UnmarshalSession

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

Directories

Path Synopsis
internal

Jump to

Keyboard shortcuts

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