parser

package
v0.59.0 Latest Latest
Warning

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

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

Compression is not this package's concern. Parse reads the bytes it is given as the format it is told, so a compressed file is unwrapped first, by filesql.OpenReader for a path or by filesql.CompressionType.NewReader for a stream whose codec the caller knows. DetectFileType looks through a compression extension for the same reason: the codec says how to read the bytes, not what they spell.

It is internal to this module and is used by filesql and by prep.

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

A load does not come through here for that reason: filesql reads CSV, TSV, JSONL, JSON arrays and Parquet in chunks through internal/reader, and this package is the whole-table door, for a caller that wants the table itself.

One table per parse

A TableData is one table. A workbook of several sheets therefore contributes one of them -- the first the sheet policy admits -- and the rest are not read. Use filesql to load a workbook as one table per sheet.

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))

Index

Examples

Constants

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 ErrEmptyData = errors.New("input holds no table")

ErrEmptyData reports input that holds no table: a file with nothing in it, a workbook with no sheet or whose sheet carries no header, a Parquet file with no schema, or LTSV whose lines are none of them records.

Every wording the read side has for that condition matches this one sentinel, because a caller that wants to tell "there was nothing to load" from "the file is broken" cannot be asked to know which of them a given format says. Matching the wording is what a caller had to do before, which put a list of this package's messages inside a package that cannot see them.

View Source
var ErrNilReader = errors.New("reader cannot be nil")

ErrNilReader reports a Parse called with no input to read.

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.

View Source
var ErrUnsupportedFileType = errors.New("unsupported file type")

ErrUnsupportedFileType reports a FileType this package does not parse.

Functions

This section is empty.

Types

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

type ExcelSheet = reader.ExcelSheet

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

type ExcelSheetPolicy

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 FileType

type FileType int

FileType names an input format. It says nothing about compression: a gzipped CSV and a plain CSV are both CSV, and a compressed stream is decompressed by the caller before it reaches Parse.

It used to name a format and a codec together, one constant for each of the fifty-six combinations, which put the cross product in the type and left five switches to be written out by hand over all of it. Adding a codec meant seven new constants and an edit to every one of those switches.

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

	// Unsupported represents an unsupported file type.
	Unsupported
)

func DetectFileType

func DetectFileType(path string) FileType

DetectFileType reports the format a path names, looking through any compression extension: "data.csv" and "data.csv.gz" are both CSV, since the codec says how to read the bytes and not what they spell. A path naming no format this package reads answers Unsupported.

Example
package main

import (
	"fmt"

	"github.com/nao1215/filesql/internal/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)
	}
	// A compression extension is looked through: the codec says how to read the
	// bytes, not what they spell.
	

func (FileType) String

func (ft FileType) String() string

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

type ParseOption

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

func WithExcelSheetPolicy(policy ExcelSheetPolicy) ParseOption

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

Parse takes the first sheet the policy admits and does not read the rest, so this narrows the choice rather than widening what comes back.

Example:

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

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
	// Nulls marks which cells hold nothing rather than an empty value
	// (Nulls[row][column]), parallel to Records when it is not nil.
	//
	// It is nil for every format but Parquet, which is the only one here with a
	// null of its own; the rest spell a missing value as an empty field, which
	// is a value. A nil mask therefore says the format has no nulls rather than
	// that this file has none, and a caller that ignores the field reads what it
	// always read: a null renders as the empty string in Records either way.
	Nulls [][]bool
}

TableData contains the parsed data from a file.

Example (ColumnTypes)
package main

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/internal/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.

A TableData is one table, so a workbook contributes one sheet: the first the sheet policy admits, in the workbook's own order. The others are not read and nothing here reports them. filesql.Open makes a table per sheet, and filesql.ExcelSheetsInReader says what a workbook holds without loading it.

Values are spelled the way the format reads them rather than the way SQLite stores them, which shows in Parquet: a whole float comes back as "2" and a boolean as "true". A load spells the same cells for SQLite's affinity, so feeding Records into a CSV and loading that is not the same as loading the Parquet file.

A compressed stream is the caller's to unwrap. Parse reads the bytes it is given as the format it is told, so a gzipped file is opened through filesql.OpenReader, or through filesql.CompressionType.NewReader for a stream whose codec the caller already knows, and the reader that comes back is what Parse reads.

A text encoding is not the caller's, and Parse reads one the way filesql.Open reads one. A leading byte-order mark decides it: a UTF-8 mark is stripped rather than left in the first column name, and a UTF-16 file is transcoded. What follows has to be UTF-8, because a TableData holds characters and nothing in a byte stream says which other encoding it might be; a Shift-JIS file, or any stray byte, is refused with an error matching filesql.ErrInvalidUTF8 that names the byte and its offset. Transcode such a file before parsing it. Parquet and XLSX carry their own container and are read as bytes.

Example:

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

import (
	"fmt"
	"strings"

	"github.com/nao1215/filesql/internal/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/internal/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/internal/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