parser

package
v0.44.0 Latest Latest
Warning

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

Go to latest
Published: Aug 21, 2026 License: MIT Imports: 12 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.

Documentation

Overview

Package parser provides file parsing functionality for various tabular data formats. It supports CSV, TSV, LTSV, XLSX, Parquet, JSON, and JSONL files, with optional compression (gzip, bzip2, xz, zstd, zlib, snappy, s2, lz4).

This package can be used by filesql, prep, frame, or any application that needs to parse tabular data files.

Memory Considerations

All parsing functions in this package load the entire dataset into memory. This design is intentional for simplicity and compatibility with formats that require random access (Parquet, XLSX), but has implications for large files:

  • CSV/TSV/LTSV: Entire file content is read into memory
  • XLSX: Entire workbook is loaded (Excel files can be large even with few rows)
  • Parquet: Entire file is read into memory for random access

For files larger than available memory, consider:

  • Using streaming APIs for CSV/TSV
  • Pre-filtering or splitting large files before processing
  • Increasing available memory for the process

Example usage

f, _ := os.Open("data.csv")
defer f.Close()
result, err := parser.Parse(f, parser.CSV)
if err != nil {
    log.Fatal(err)
}
fmt.Println("Columns:", result.Headers)
fmt.Println("Rows:", len(result.Records))

Type Conversion

Use ParseValue to convert string records to typed Go values based on ColumnType.

Index

Examples

Constants

View Source
const (
	ExtCSV     = ".csv"
	ExtTSV     = ".tsv"
	ExtLTSV    = ".ltsv"
	ExtParquet = ".parquet"
	ExtXLSX    = ".xlsx"
	ExtJSON    = ".json"
	ExtJSONL   = ".jsonl"
	ExtGZ      = ".gz"
	ExtBZ2     = ".bz2"
	ExtXZ      = ".xz"
	ExtZSTD    = ".zst"
	ExtZLIB    = ".z"
	ExtSNAPPY  = ".snappy"
	ExtS2      = ".s2"
	ExtLZ4     = ".lz4"
)

File extensions

View Source
const (
	// ExcelSheetPolicyAll reads every sheet, hidden or not. It is the zero
	// value, so a caller that names no policy keeps the behavior this package
	// had before the setting existed.
	ExcelSheetPolicyAll = reader.ExcelSheetPolicyAll

	// ExcelSheetPolicyVisibleOnly reads only the sheets a workbook shows.
	//
	// Excel separates "hidden", which a user can undo from the sheet tabs, from
	// "very hidden", which only the VBA editor can. The library underneath
	// reports one boolean covering both, so neither does this package: a sheet
	// the workbook does not show is left out under this policy, and no claim is
	// made about which of the two ways it was hidden.
	ExcelSheetPolicyVisibleOnly = reader.ExcelSheetPolicyVisibleOnly
)

Variables

View Source
var ErrCSVSyntax = reader.ErrCSVSyntax

ErrCSVSyntax reports a file that is not CSV: a quote where a field cannot hold one, or a quoted field that never closes.

View Source
var ErrTSVSyntax = errors.New("invalid TSV syntax")

ErrTSVSyntax reports tab-separated input that does not describe a table: a record whose field count differs from the header's. It is the counterpart of ErrCSVSyntax, which a caller can already match for the same shape in CSV; without one, the two formats reported the same fault in two ways, and TSV reported it as no fault at all.

View Source
var ErrTSVUnrepresentable = errors.New("value cannot be represented in TSV")

ErrTSVUnrepresentable reports a value that tab-separated values cannot hold: one containing a tab, which is the delimiter, or a line break, which ends the record. There is no escape for either.

Functions

func IsCompressed added in v0.18.0

func IsCompressed(ft FileType) bool

IsCompressed returns true if the file type is compressed.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql/parser"
)

func main() {
	types := []parser.FileType{
		parser.CSV,
		parser.CSVGZ,
		parser.Parquet,
		parser.ParquetZSTD,
	}

	for _, ft := range types {
		fmt.Printf("%s compressed: %v\n", ft, parser.IsCompressed(ft))
	}
}
Output:
CSV compressed: false
CSV (gzip) compressed: true
Parquet compressed: false
Parquet (zstd) compressed: true

func NormalizeLineEndings added in v0.40.0

func NormalizeLineEndings(r io.Reader) io.Reader

NormalizeLineEndings wraps reader so a file whose lines end with a lone carriage return is read as lines rather than as one very long line.

CSV readers, and everything here that splits on "\n", understand LF and CRLF. A file written with the classic Mac OS 9 convention has neither, so without this the whole file parses as a single line: the data folds into the column names and the table comes out with zero rows, at no error.

The convention is decided from the start of the file rather than by translating every carriage return that appears, because a carriage return inside a quoted field is data.

func NormalizeXLSXDates added in v0.42.0

func NormalizeXLSXDates(f *excelize.File, sheet string, rows [][]string) [][]string

NormalizeXLSXDates rewrites the date cells of a sheet's rows into ISO 8601, leaving every other cell as GetRows rendered it.

A workbook stores a date as a serial number and a number format, and GetRows applies the format: the same day arrives as "03-15-23", "2023-03-15", or "Mar 15" depending on how the sheet was formatted, and none of the first two forms sorts chronologically. ISO 8601 is the form the datetime inference recognizes, which is what makes the column a datetime rather than text.

Only cells the workbook itself calls dates are touched. A number formatted as a number, and text that merely looks like a date, are left alone.

func ParseValue

func ParseValue(value string, colType ColumnType) any

ParseValue converts a string value to the appropriate Go type based on ColumnType. This function is useful for converting string records from TableData to typed values.

Conversion rules:

  • TypeInteger: returns int64, or original string if parsing fails
  • TypeReal: returns float64, or original string if parsing fails
  • TypeDatetime: returns string (caller can parse with time.Parse if needed)
  • TypeText: returns string as-is
  • Empty values return nil
Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql/parser"
)

func main() {
	// Integer column
	intVal := parser.ParseValue("42", parser.TypeInteger)
	fmt.Printf("Integer: %v (%T)\n", intVal, intVal)

	// Real column
	realVal := parser.ParseValue("3.14", parser.TypeReal)
	fmt.Printf("Real: %v (%T)\n", realVal, realVal)

	// Text column
	textVal := parser.ParseValue("hello", parser.TypeText)
	fmt.Printf("Text: %v (%T)\n", textVal, textVal)

	// Empty value returns nil
	nilVal := parser.ParseValue("", parser.TypeInteger)
	fmt.Printf("Empty: %v\n", nilVal)
}
Output:
Integer: 42 (int64)
Real: 3.14 (float64)
Text: hello (string)
Empty: <nil>

func SelectExcelSheets added in v0.32.0

func SelectExcelSheets(f ExcelSheetSource, policy ExcelSheetPolicy) (loaded, skipped []string, err error)

SelectExcelSheets returns the sheets policy admits, in workbook order, and the names it left out.

Every Excel read goes through this rather than filtering at its own call to the sheet list, so "which sheets does this workbook contribute?" has one answer whatever opened the file.

func WriteTSVRecord added in v0.40.0

func WriteTSVRecord(w io.Writer, record []string) error

WriteTSVRecord writes one record as a line of tab-separated fields, and reports a field the format cannot hold rather than writing something else.

A CSV writer would quote such a field instead, and to this reader a quote is data, so what came back would carry the quotes the writer added.

func WriteTSVRecordLineEnding added in v0.44.0

func WriteTSVRecordLineEnding(w io.Writer, record []string, lineEnding string) error

WriteTSVRecordLineEnding is WriteTSVRecord with the line terminator named, for a writer that has to keep the one its destination already uses: a file rewritten with a different terminator differs on every line, including the ones nobody edited.

An empty lineEnding writes "\n", so a zero value behaves as WriteTSVRecord does rather than running the records together.

Types

type CSVReader added in v0.44.0

type CSVReader = reader.CSVReader

CSVReader reads comma-separated records, keeping the bytes between quotes exactly as the file has them.

encoding/csv is otherwise the right answer, and this exists for one difference: it removes a carriage return that precedes a line feed inside a quoted field. That is documented and callers depend on it, but it makes a value change on the way through -- a spreadsheet export whose address cell holds a CRLF line break comes back holding LF, so saving the file rewrites a row nobody edited. A line break inside quotes is field data, and this reader treats it as such.

func NewCSVReader added in v0.44.0

func NewCSVReader(r io.Reader) *CSVReader

NewCSVReader returns a reader over the comma-separated records in r.

type ColumnType

type ColumnType int

ColumnType represents the inferred type of a column.

const (
	// TypeText represents text/string column type.
	TypeText ColumnType = iota
	// TypeInteger represents integer column type.
	TypeInteger
	// TypeReal represents floating-point column type.
	TypeReal
	// TypeDatetime represents datetime column type.
	TypeDatetime
)

func (ColumnType) String

func (ct ColumnType) String() string

String returns the string representation of ColumnType.

type ExcelSheet added in v0.32.0

type ExcelSheet = reader.ExcelSheet

ExcelSheet is one sheet of a workbook and whether the workbook shows it.

func ExcelSheets added in v0.32.0

func ExcelSheets(f ExcelSheetSource) ([]ExcelSheet, error)

ExcelSheets returns every sheet of the workbook in the order the workbook stores them, with the visibility it reports for each.

A visibility that cannot be read is an error, not an assumption. Defaulting to visible would load a sheet the workbook hides; defaulting to hidden would drop one it shows.

type ExcelSheetPolicy added in v0.32.0

type ExcelSheetPolicy = reader.ExcelSheetPolicy

ExcelSheetPolicy decides which sheets of a workbook a read looks at.

A workbook can hide a sheet, and hiding one is how a spreadsheet keeps scratch calculations, lookup tables, and stale drafts out of the way of the sheets it means to present. Whether those belong in a database is the caller's judgment rather than something this package can decide, so which sheets to take is a setting and not a rule.

type ExcelSheetSource added in v0.32.0

type ExcelSheetSource = reader.ExcelSheetSource

ExcelSheetSource is the part of an open workbook that sheet selection reads.

It is an interface rather than the concrete workbook type for two reasons: the excelize dependency stays out of this package's signatures, and the selection rules -- order, filtering, and what happens when a visibility cannot be read -- become testable without a workbook that has to be coaxed into failing.

type FileType

type FileType int

FileType represents supported file types including compression variants.

const (
	// CSV represents CSV file type.
	CSV FileType = iota
	// TSV represents TSV file type.
	TSV
	// LTSV represents LTSV (Labeled Tab-Separated Values) file type.
	LTSV
	// Parquet represents Apache Parquet file type.
	Parquet
	// XLSX represents Excel XLSX file type.
	XLSX
	// JSON represents JSON file type.
	JSON
	// JSONL represents JSON Lines file type.
	JSONL

	// CSVGZ represents gzip-compressed CSV file type.
	CSVGZ
	// CSVBZ2 represents bzip2-compressed CSV file type.
	CSVBZ2
	// CSVXZ represents xz-compressed CSV file type.
	CSVXZ
	// CSVZSTD represents zstd-compressed CSV file type.
	CSVZSTD

	// TSVGZ represents gzip-compressed TSV file type.
	TSVGZ
	// TSVBZ2 represents bzip2-compressed TSV file type.
	TSVBZ2
	// TSVXZ represents xz-compressed TSV file type.
	TSVXZ
	// TSVZSTD represents zstd-compressed TSV file type.
	TSVZSTD

	// LTSVGZ represents gzip-compressed LTSV file type.
	LTSVGZ
	// LTSVBZ2 represents bzip2-compressed LTSV file type.
	LTSVBZ2
	// LTSVXZ represents xz-compressed LTSV file type.
	LTSVXZ
	// LTSVZSTD represents zstd-compressed LTSV file type.
	LTSVZSTD

	// ParquetGZ represents gzip-compressed Parquet file type.
	ParquetGZ
	// ParquetBZ2 represents bzip2-compressed Parquet file type.
	ParquetBZ2
	// ParquetXZ represents xz-compressed Parquet file type.
	ParquetXZ
	// ParquetZSTD represents zstd-compressed Parquet file type.
	ParquetZSTD

	// XLSXGZ represents gzip-compressed XLSX file type.
	XLSXGZ
	// XLSXBZ2 represents bzip2-compressed XLSX file type.
	XLSXBZ2
	// XLSXXZ represents xz-compressed XLSX file type.
	XLSXXZ
	// XLSXZSTD represents zstd-compressed XLSX file type.
	XLSXZSTD

	// CSVZLIB represents zlib-compressed CSV file type.
	CSVZLIB
	// TSVZLIB represents zlib-compressed TSV file type.
	TSVZLIB
	// LTSVZLIB represents zlib-compressed LTSV file type.
	LTSVZLIB
	// ParquetZLIB represents zlib-compressed Parquet file type.
	ParquetZLIB
	// XLSXZLIB represents zlib-compressed XLSX file type.
	XLSXZLIB

	// CSVSNAPPY represents snappy-compressed CSV file type.
	CSVSNAPPY
	// TSVSNAPPY represents snappy-compressed TSV file type.
	TSVSNAPPY
	// LTSVSNAPPY represents snappy-compressed LTSV file type.
	LTSVSNAPPY
	// ParquetSNAPPY represents snappy-compressed Parquet file type.
	ParquetSNAPPY
	// XLSXSNAPPY represents snappy-compressed XLSX file type.
	XLSXSNAPPY

	// CSVS2 represents s2-compressed CSV file type.
	CSVS2
	// TSVS2 represents s2-compressed TSV file type.
	TSVS2
	// LTSVS2 represents s2-compressed LTSV file type.
	LTSVS2
	// ParquetS2 represents s2-compressed Parquet file type.
	ParquetS2
	// XLSXS2 represents s2-compressed XLSX file type.
	XLSXS2

	// CSVLZ4 represents lz4-compressed CSV file type.
	CSVLZ4
	// TSVLZ4 represents lz4-compressed TSV file type.
	TSVLZ4
	// LTSVLZ4 represents lz4-compressed LTSV file type.
	LTSVLZ4
	// ParquetLZ4 represents lz4-compressed Parquet file type.
	ParquetLZ4
	// XLSXLZ4 represents lz4-compressed XLSX file type.
	XLSXLZ4

	// JSONGZ represents gzip-compressed JSON file type.
	JSONGZ
	// JSONBZ2 represents bzip2-compressed JSON file type.
	JSONBZ2
	// JSONXZ represents xz-compressed JSON file type.
	JSONXZ
	// JSONZSTD represents zstd-compressed JSON file type.
	JSONZSTD
	// JSONZLIB represents zlib-compressed JSON file type.
	JSONZLIB
	// JSONSNAPPY represents snappy-compressed JSON file type.
	JSONSNAPPY
	// JSONS2 represents s2-compressed JSON file type.
	JSONS2
	// JSONLZ4 represents lz4-compressed JSON file type.
	JSONLZ4

	// JSONLGZ represents gzip-compressed JSONL file type.
	JSONLGZ
	// JSONLBZ2 represents bzip2-compressed JSONL file type.
	JSONLBZ2
	// JSONLXZ represents xz-compressed JSONL file type.
	JSONLXZ
	// JSONLZSTD represents zstd-compressed JSONL file type.
	JSONLZSTD
	// JSONLZLIB represents zlib-compressed JSONL file type.
	JSONLZLIB
	// JSONLSNAPPY represents snappy-compressed JSONL file type.
	JSONLSNAPPY
	// JSONLS2 represents s2-compressed JSONL file type.
	JSONLS2
	// JSONLLZ4 represents lz4-compressed JSONL file type.
	JSONLLZ4

	// Unsupported represents unsupported file type.
	Unsupported
)

func BaseFileType

func BaseFileType(ft FileType) FileType

BaseFileType returns the base file type without compression.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql/parser"
)

func main() {
	types := []parser.FileType{
		parser.CSV,
		parser.CSVGZ,
		parser.TSVBZ2,
		parser.ParquetZSTD,
	}

	for _, ft := range types {
		base := parser.BaseFileType(ft)
		fmt.Printf("%s -> %s\n", ft, base)
	}
}
Output:
CSV -> CSV
CSV (gzip) -> CSV
TSV (bzip2) -> TSV
Parquet (zstd) -> Parquet

func DetectFileType

func DetectFileType(path string) FileType

DetectFileType detects file type from path extension, including compression variants.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql/parser"
)

func main() {
	paths := []string{
		"data.csv",
		"data.csv.gz",
		"report.xlsx",
		"logs.ltsv.zst",
		"analytics.parquet",
	}

	for _, path := range paths {
		ft := parser.DetectFileType(path)
		fmt.Printf("%s -> %s\n", path, ft)
	}
}
Output:
data.csv -> CSV
data.csv.gz -> CSV (gzip)
report.xlsx -> XLSX
logs.ltsv.zst -> LTSV (zstd)
analytics.parquet -> Parquet

func (FileType) String

func (ft FileType) String() string

String returns a human-readable string representation of the FileType.

type ParseOption added in v0.32.0

type ParseOption func(*parseConfig)

ParseOption adjusts how Parse reads a source. Options only affect the formats they name; one that has nothing to say about the given fileType is ignored.

func WithExcelSheetPolicy added in v0.32.0

func WithExcelSheetPolicy(policy ExcelSheetPolicy) ParseOption

WithExcelSheetPolicy decides which sheets of a workbook Parse may take its table from. It has no effect on other formats.

Example:

result, err := parser.Parse(f, parser.XLSX, parser.WithExcelSheetPolicy(parser.ExcelSheetPolicyVisibleOnly))

type TSVReader added in v0.40.0

type TSVReader = reader.TSVReader

TSVReader reads tab-separated records, taking every field literally.

TSV has no quoting. IANA's text/tab-separated-values says a field is the bytes between two tabs, so a double quote in one is an ordinary character. Reading TSV with a CSV reader brings CSV's quote handling with it: a value as plain as 5'9" tall fails the whole import with `bare " in non-quoted-field`.

func NewTSVReader added in v0.40.0

func NewTSVReader(r io.Reader) *TSVReader

NewTSVReader returns a reader over the tab-separated records in r.

type TableData

type TableData struct {
	// Headers contains the column names in order.
	Headers []string
	// Records contains the data rows. Each record is a slice of string values.
	Records [][]string
	// ColumnTypes contains the inferred types for each column.
	// The length matches Headers.
	ColumnTypes []ColumnType
}

TableData contains the parsed data from a file.

Example (ColumnTypes)
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/parser"
)

func main() {
	csvData := `id,name,score,date
1,Alice,85.5,2024-01-15
2,Bob,92.0,2024-01-16
3,Charlie,78.5,2024-01-17`

	result, err := parser.Parse(strings.NewReader(csvData), parser.CSV)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	for i, header := range result.Headers {
		fmt.Printf("%s: %s\n", header, result.ColumnTypes[i])
	}
}
Output:
id: INTEGER
name: TEXT
score: REAL
date: DATETIME

func Parse

func Parse(input io.Reader, fileType FileType, opts ...ParseOption) (result *TableData, err error)

Parse reads data from an io.Reader and returns parsed results. The fileType parameter specifies the format and compression of the data.

Example:

f, _ := os.Open("data.csv.gz")
defer f.Close()
result, err := parser.Parse(f, parser.CSVGZ)
Example (Csv)
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/parser"
)

func main() {
	csvData := `name,age,score
Alice,30,85.5
Bob,25,92.0
Charlie,35,78.5`

	result, err := parser.Parse(strings.NewReader(csvData), parser.CSV)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Headers:", result.Headers)
	fmt.Println("Records:", len(result.Records))
	fmt.Println("First row:", result.Records[0])
}
Output:
Headers: [name age score]
Records: 3
First row: [Alice 30 85.5]
Example (Ltsv)
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/parser"
)

func main() {
	ltsvData := `host:192.168.1.1	method:GET	path:/index.html
host:192.168.1.2	method:POST	path:/api/users`

	result, err := parser.Parse(strings.NewReader(ltsvData), parser.LTSV)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Headers:", result.Headers)
	fmt.Println("First row:", result.Records[0])
}
Output:
Headers: [host method path]
First row: [192.168.1.1 GET /index.html]
Example (Tsv)
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/parser"
)

func main() {
	tsvData := `id	product	price
1	Laptop	999.99
2	Mouse	29.99
3	Keyboard	79.99`

	result, err := parser.Parse(strings.NewReader(tsvData), parser.TSV)
	if err != nil {
		fmt.Println("Error:", err)
		return
	}

	fmt.Println("Headers:", result.Headers)
	fmt.Println("Records:", len(result.Records))
}
Output:
Headers: [id product price]
Records: 3

Directories

Path Synopsis
Package ach provides bidirectional conversion between ACH files and TableData.
Package ach provides bidirectional conversion between ACH files and TableData.
Package wire provides bidirectional conversion between Fedwire files and TableData.
Package wire provides bidirectional conversion between Fedwire files and TableData.

Jump to

Keyboard shortcuts

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