reader

package
v0.50.0 Latest Latest
Warning

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

Go to latest
Published: Aug 27, 2026 License: MIT Imports: 21 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 reader turns a file of a supported format into the rows of a table.

It is the one implementation of every format filesql reads. The root package read files in chunks on the way into SQLite while the parser package read the same formats whole, so each format was written twice and the two drifted: XLSX dates were normalized on one path and not the other, and a codec or a rule fixed in one was still wrong in the other.

A read hands the caller its rows a chunk at a time and returns the type every column requires once the last row has been seen. Reading in chunks is what a load needs; a caller that wants the whole table collects the chunks, which is cheaper than the reverse.

Index

Constants

View Source
const DefaultChunkSize = 1000

DefaultChunkSize is how many rows a chunk holds when the caller names no size.

View Source
const JSONDataColumn = "data"

JSONDataColumn is the one column a JSON or JSONL table has: the raw JSON of each element, held as text.

The document is stored as it was written and read back with SQLite's json_extract(), which is what makes an arbitrarily nested document queryable without a schema:

SELECT json_extract(data, '$.address.city') FROM my_json_table;

Variables

View Source
var ErrCSVSyntax = errors.New("invalid CSV syntax")

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 ErrRecordTooLong = errors.New("record too long")

ErrRecordTooLong reports a record past maxRecordSize. It is separate from the syntax errors because the file may be perfectly well formed and simply larger than this reader will hold.

Functions

func ASCIIFold

func ASCIIFold(s string) string

ASCIIFold lowercases the ASCII letters in s and leaves every other byte as it is, which is how SQLite compares two column names: its default case folding stops at ASCII, so "ä" and "Ä" stay two names. Folding with strings.ToLower would make them one and refuse a header SQLite accepts.

Case has to be folded somewhere, because leaving it out did not make "ID" and "id" two columns: it moved the refusal to SQLite, which reported it as a failed CREATE TABLE wrapped in a database-operation error -- no sentinel to match and no column position, which is the outcome this check exists to replace.

func LTSVLabelKey

func LTSVLabelKey(label string) string

LTSVLabelKey is how two LTSV labels are compared for being one column.

LTSV carries its labels on every record rather than in a header, so the duplicate check runs per record and had its own comparison, which was exact. A record holding "A:1\ta:2" therefore reached SQLite, which folds ASCII case, and failed as a raw CREATE TABLE error with no duplicate-column sentinel to match -- the outcome the check exists to replace, left in the one format whose labels do not go through ValidateColumnNames.

func NoExcelSheetsError

func NoExcelSheetsError(f ExcelSheetSource, policy ExcelSheetPolicy) error

NoExcelSheetsError explains a workbook that contributed nothing. It separates one with no sheets at all from one whose sheets were all left out by the policy, because the two need different things done about them: the first file is broken, the second is a setting the caller chose.

func NormalizeLineEndings

func NormalizeLineEndings(reader io.Reader, format Format) 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. Only what sits outside quotes counts, on both sides of the question: a file is read this way when its first 64 KiB hold a carriage return outside quotes and no line feed outside them, and only carriage returns outside quotes are translated. A first record longer than that window is left alone rather than guessed at: reading it as one line is what happens today, while a wrong guess would rewrite data.

Which is why the format is needed: only CSV has a quote. TSV takes a field as the bytes between two tabs and LTSV as the bytes up to the next tab, so a double quote in either is an ordinary character, and honoring it let one of them swallow every terminator after it -- a three-row one-column file loaded as one row. The save side asks the same question of a file it is about to overwrite and draws the line in the same place.

func NormalizeXLSXDates

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. A column of dates became a column of format-dependent text, so ORDER BY sorted it lexically and a comparison against an ISO literal never matched.

ISO 8601 is the form the datetime inference already recognizes, which is what makes the column a datetime rather than text. A cell whose time of day is midnight is written as a plain date, because that is what a date cell holds; anything else keeps its time.

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 QuoteFields added in v0.49.0

func QuoteFields(fields []string) string

QuoteFields spells the fields of a record for a message, quoted so a field that is empty or only spaces is visible and shortened so a long line does not become the whole error. It is exported because the caller that decides what becomes of such a record words its own refusal, and one wording of the same list is better than two.

func SQLiteFloatText

func SQLiteFloatText(f float64, bitSize int) string

SQLiteFloatText renders a float at bitSize so SQLite's REAL affinity converts it back to the same number, which "%g" does not for the three values that have no decimal spelling. It is what a load binds and what a dump writes, so a value that survives one survives the other.

The column is declared REAL from the Parquet schema, and SQLite applies that affinity to the text an import binds: "+Inf" is not a number to it, so the cell was stored as TEXT inside a REAL column and typeof() answered "text" for a value the file held as a double. "9e999" overflows to infinity when SQLite parses it, which is the only spelling that survives.

NaN renders as empty, the same as a null, because SQLite has no NaN at all: a computed one becomes NULL there, so NULL is what the value already means in the destination. Keeping the word would leave the same TEXT-in-a-REAL-column mismatch this exists to remove.

func SelectExcelSheets

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. That matters most for the caller that maps sheets onto table names: the names it must keep apart are the ones actually loaded, and a sheet nobody reads cannot collide with one that is read.

func ValidateColumnNames

func ValidateColumnNames(columns []string) error

ValidateColumnNames reports a header that names one column twice.

The message quotes the name and gives its 1-based position, because a header can duplicate the empty name -- two unnamed columns -- and an unquoted empty name printed nothing at all after the colon.

Two names are the same column if either comparison says so, and the two are kept apart rather than combined into one key. Whitespace is filesql's own rule -- " name " and "name" are one name typed twice -- while case is SQLite's, because SQLite is what ends up holding the columns. Folding a trimmed name would apply both at once and refuse " A" beside "a", which neither rule refuses on its own and which SQLite keeps as two columns.

Types

type CSVReader

type CSVReader struct {

	// Comma separates fields. The zero value reads ',' and only a single-byte
	// delimiter is supported, which is what the callers use.
	Comma rune
	// FieldsPerRecord follows encoding/csv: zero takes the count from the first
	// record and requires the rest to match, a negative value allows any count,
	// and a positive value requires that many.
	FieldsPerRecord int
	// contains filtered or unexported fields
}

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

func NewCSVReader(r io.Reader) *CSVReader

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

func (*CSVReader) Read

func (c *CSVReader) Read() ([]string, error)

Read returns the next record, or io.EOF when there are none left. A blank line is not a record and is skipped, which is what encoding/csv does.

func (*CSVReader) ReadAll

func (c *CSVReader) ReadAll() ([][]string, error)

ReadAll returns every remaining record.

type Chunk

type Chunk struct {
	// Header names the columns, and is the same for every chunk of one read.
	Header []string
	// Records are the rows of this chunk. A record may be shorter than the
	// header, which means its last cells are missing; it is never longer.
	Records [][]string
	// Types is what every row read so far, this chunk included, requires of
	// each column. A format with a schema states it from the first chunk; one
	// without can only widen it as it reads, and the last chunk's is final.
	Types []infer.Type
	// Nulls, when non-nil, marks which cells hold SQL NULL rather than text
	// (Nulls[row][col]). Formats with no null of their own leave it nil.
	Nulls [][]bool
}

Chunk is one run of a table's rows on the way to its caller.

type Emit

type Emit func(*Chunk) error

Emit receives one chunk. Returning an error stops the read and is what the read returns.

type Error

type Error struct {
	// Kind is what went wrong, in a form a caller can map onto its own sentinel.
	Kind Kind
	// Msg says what went wrong, without naming a sentinel: a caller prefixes
	// its own.
	Msg string
	// Err is the cause, when the failure came from underneath.
	Err error
}

Error is a read that failed, and why.

func (*Error) Error

func (e *Error) Error() string

Error renders the message and the cause under it.

func (*Error) Unwrap

func (e *Error) Unwrap() error

Unwrap returns the cause, so errors.Is reaches whatever it carries.

type ExcelSheet

type ExcelSheet struct {
	// Name is the sheet name as the workbook stores it, before any sanitizing a
	// caller applies to turn it into a table name.
	Name string
	// Visible is false for a sheet the workbook does not show, whether it is
	// hidden or very hidden.
	Visible bool
}

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

func ExcelSheets

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. Either way the caller is told something untrue about the file, which is worse than being told the file could not be understood.

type ExcelSheetPolicy

type ExcelSheetPolicy int

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.

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 ExcelSheetPolicy = iota

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

func (ExcelSheetPolicy) String

func (p ExcelSheetPolicy) String() string

String renders the policy for messages and logs.

type ExcelSheetSource

type ExcelSheetSource interface {
	// GetSheetList returns the sheet names in the order the workbook stores them.
	GetSheetList() []string
	// GetSheetVisible reports whether the workbook shows the named sheet.
	GetSheetVisible(sheet string) (bool, error)
}

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 Format

type Format int

Format is the file format a source is read as. Compression is not part of it: a caller unwraps the codec before reading.

const (
	// FormatCSV is comma-separated values.
	FormatCSV Format = iota
	// FormatTSV is tab-separated values.
	FormatTSV
	// FormatLTSV is labeled tab-separated values.
	FormatLTSV
	// FormatParquet is Apache Parquet.
	FormatParquet
	// FormatXLSX is an Excel workbook.
	FormatXLSX
	// FormatJSON is one JSON document.
	FormatJSON
	// FormatJSONL is one JSON value per line.
	FormatJSONL
)

func (Format) String

func (f Format) String() string

String names the format the way an error message does.

type Kind

type Kind int

Kind classifies why a read failed, so a caller can report it with the sentinel error its own package already has. The message is separate from the kind for the same reason: the wording is this package's, the sentinel is the caller's.

const (
	// KindParse is input that does not describe a table of the format it claims.
	KindParse Kind = iota
	// KindEmpty is input that holds no table at all.
	KindEmpty
	// KindInvalidData is a value the format cannot hold.
	KindInvalidData
	// KindDuplicateColumn is a header that names one column twice.
	KindDuplicateColumn
	// KindUnsupported is a format this package does not read.
	KindUnsupported
)

type Options

type Options struct {
	// ChunkSize is how many rows a chunk holds. A value below one reads
	// DefaultChunkSize rows at a time; a chunk of no rows would read forever.
	ChunkSize int
	// Reconcile handles a delimited record of the wrong width.
	Reconcile Reconcile
	// Unlabeled handles an LTSV record holding a field that names no label. A
	// nil Unlabeled refuses such a record, since a read with no policy of its
	// own has only the strict answer available: the field is data the table has
	// no column for, and keeping the record would drop it without a word.
	Unlabeled Unlabeled
	// ExcelSheetPolicy decides which sheets of a workbook a read may take its
	// table from.
	ExcelSheetPolicy ExcelSheetPolicy
	// Rendering says how a value that is not already text is spelled.
	Rendering Rendering
	// contains filtered or unexported fields
}

Options are the settings a read honors. The zero value reads with the default chunk size, keeps every record as it comes, and takes any sheet of a workbook.

type Reconcile

type Reconcile func(record []string, want, rowNum int) (out []string, skip bool, err error)

Reconcile decides what becomes of a delimited record whose field count differs from the header's: the record to keep, whether to drop it, or the error that ends the read. A nil Reconcile keeps every record as it is, which leaves a short one short and a long one long.

type Rendering

type Rendering int

Rendering says how a value that is not already text is spelled.

const (
	// RenderPlain spells a value the way the format reads it: a boolean as
	// "true" or "false", and a whole float without a decimal point.
	RenderPlain Rendering = iota
	// RenderSQLite spells a value so SQLite's column affinity converts it back
	// to what the file holds: a boolean as 1 or 0, a whole float with a ".0" so
	// its column stays REAL, and a NaN as NULL, which is what SQLite has in
	// place of one.
	RenderSQLite
)

type Result

type Result struct {
	// Header names the columns. For a format that carries no header line it is
	// what the data itself named.
	Header []string
	// Types is what every row of the input requires of each column. It is final:
	// no row was left unread when it was decided.
	Types []infer.Type
	// Rows is how many records were emitted.
	Rows int
	// Skipped is how many records Reconcile dropped, and Total how many data
	// records the input held, dropped ones included. Skipping is an instruction,
	// and an instruction that reports nothing leaves one dropped row and most of
	// the file dropped looking the same.
	Skipped int
	Total   int
	// EmptyInput reports a source that held no value at all, which JSON and
	// JSONL alone tell apart from a document saying there is nothing.
	EmptyInput bool
}

Result is what a read says about the table it produced.

func Read

func Read(src io.Reader, format Format, opts Options, emit Emit) (Result, error)

Read reads src as format, handing each chunk of rows to emit, and returns what the whole input requires of its columns.

The types come last because they are not known until the last row has been read: a column is declared once, after the whole input has been seen, so where a chunk boundary falls cannot change what a table holds.

A read always emits at least one chunk, even for input that is nothing but a header, so a caller that creates its table from the first chunk always gets one to create it from.

type TSVReader

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

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

func NewTSVReader(r io.Reader) *TSVReader

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

func (*TSVReader) Read

func (t *TSVReader) Read() ([]string, error)

Read returns the next record, or io.EOF when there are none left.

A blank line is a record only in a one-column file, where it is that column's empty value. With more columns it cannot be a record of that shape, so it is skipped, as a CSV reader skips it.

func (*TSVReader) ReadAll

func (t *TSVReader) ReadAll() ([][]string, error)

ReadAll returns every remaining record.

type Unlabeled added in v0.49.0

type Unlabeled func(fields []string, rowNum int) (skip bool, err error)

Unlabeled decides what becomes of an LTSV record holding a field that is not a label and a value: whether to drop the record, or the error that ends the read. fields are the offending fields as the file wrote them, so the answer can quote them.

LTSV names its columns on every record, so a field with no label is not a record of the wrong width, since there is no width to be wrong. It is the same event: the record carries something the table has no column for. It gets its own hook because the two are told apart by different questions, and because one answer has to be able to quote a field rather than count them.

type Workbook

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

Workbook is an open Excel workbook.

A workbook holds several sheets and a table holds one, so opening and reading are separate: a caller that maps every sheet onto its own table opens once and reads each sheet, and one that wants a single table reads the first sheet its policy admits.

func OpenWorkbook

func OpenWorkbook(src io.Reader) (*Workbook, error)

OpenWorkbook reads a workbook from src.

The bytes are buffered whole because the format is a zip archive that is read by random access, which a stream cannot provide.

func (*Workbook) Close

func (w *Workbook) Close() error

Close releases the workbook.

func (*Workbook) ReadSheet

func (w *Workbook) ReadSheet(name string, opts Options, emit Emit) (Result, error)

ReadSheet reads one sheet of the workbook in chunks.

A sheet holding nothing a table can be made from -- no rows, or no row that names any column -- is reported with Kind KindEmpty, so a caller loading every sheet can pass over it while one loading a single sheet can refuse.

func (*Workbook) Select

func (w *Workbook) Select(policy ExcelSheetPolicy) (loaded, skipped []string, err error)

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

func (*Workbook) Source

func (w *Workbook) Source() ExcelSheetSource

Source is the workbook as sheet selection sees it, for a caller that reports on the sheets rather than reading them.

Jump to

Keyboard shortcuts

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