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
- Variables
- func ASCIIFold(s string) string
- func BoundRecords(src io.Reader) io.Reader
- func LTSVLabelKey(label string) string
- func NameBlankColumns(columns []string) []string
- func NoExcelSheetsError(f ExcelSheetSource, policy ExcelSheetPolicy) error
- func NormalizeLineEndings(reader io.Reader, format Format) io.Reader
- func QuoteFields(fields []string) string
- func SQLiteFloatText(f float64, bitSize int) string
- func SelectExcelSheets(f ExcelSheetSource, policy ExcelSheetPolicy) (loaded, skipped []string, err error)
- func SentinelFor(kind Kind) error
- func ValidateColumnCount(columns int) error
- func ValidateColumnNames(columns []string) error
- type CSVReader
- type Chunk
- type Emit
- type Error
- type ExcelSheet
- type ExcelSheetPolicy
- type ExcelSheetSource
- type Format
- type Kind
- type Options
- type ParquetRenderer
- type Reconcile
- type Rendering
- type Result
- type SheetLayout
- type TSVReader
- type Unlabeled
- type Workbook
- func (w *Workbook) Close() error
- func (w *Workbook) File() *excelize.File
- func (w *Workbook) LayoutOf(name string, rows [][]string) SheetLayout
- func (w *Workbook) NormalizeCells(sheet string, rows [][]string) [][]string
- func (w *Workbook) ReadSheet(name string, opts Options, emit Emit) (Result, error)
- func (w *Workbook) Rows(name string) (rows [][]string, err error)
- func (w *Workbook) Select(policy ExcelSheetPolicy) (loaded, skipped []string, err error)
- func (w *Workbook) Source() ExcelSheetSource
Constants ¶
const DefaultChunkSize = 1000
DefaultChunkSize is how many rows a chunk holds when the caller names no size.
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;
const MaxColumns = 2000
MaxColumns is how many columns a table can hold, which is SQLite's SQLITE_MAX_COLUMN in the build this package uses. It is fixed when SQLite is compiled, so a wider file cannot be loaded whatever this package does; what it can do is say so in its own words, with the two numbers a caller needs, rather than letting a failed CREATE TABLE reach them -- which named the staging table this package builds for a reader and no limit at all.
Variables ¶
var ( // ErrEmptyData is input holding no table at all. ErrEmptyData = errors.New("filesql: empty data source") // ErrInvalidData is a value the format cannot hold. ErrInvalidData = errors.New("filesql: invalid data format") // ErrDuplicateColumn is a header that names one column twice. ErrDuplicateColumn = errors.New("filesql: duplicate column name") // ErrUnsupportedFormat is input this package does not read. ErrUnsupportedFormat = errors.New("filesql: unsupported file format") // ErrParsing is input that does not describe a table of the format it // claims. It is the general kind; every other kind narrows it. ErrParsing = errors.New("filesql: parsing failed") // ErrColumnMismatch is a record that does not fit the columns of its table. // It is not one of the kinds, because a record that does not fit is decided // on by the malformed-row policy rather than refused outright; it lives here // so the door that refuses it and the door that reports it name the same // sentinel. ErrColumnMismatch = errors.New("filesql: column count mismatch") )
The sentinels a read failure carries. They live here rather than in the packages that publish them because both doors into this reader answer for the same input: filesql exports them under its own names, and prep, which parses through the same reader, returns an error carrying them, so errors.Is finds the same one whichever door a caller came through.
A caller used to map Kind onto its own sentinel, and the mapping was written twice -- once by the loader, which handled every kind, and once by the parser, which handled two and let the rest through unclassified, so four classes of malformed input reached a caller of prep matching nothing at all. An Error carries its own sentinel now, and there is nothing left to map.
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.
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 ¶
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 BoundRecords ¶ added in v0.52.0
BoundRecords wraps src so one record past the bound every reader here holds to is refused. It is for a format read by a library of its own, which has no bound of its own to hold to.
func LTSVLabelKey ¶
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 NameBlankColumns ¶ added in v0.52.0
NameBlankColumns gives a name to every column whose header cell is empty.
A blank header names nothing, so there is no name typed twice in a header with two of them -- but two empty names are equal, and the duplicate check refused the file with a message about a name it never wrote. A spreadsheet exported with spacer columns, and a CSV whose header ends in two commas, both arrive that way.
The name is the column's position, which is distinct on its own and is something the caller can write in a query. It is checked against the names the file did write, so a header saying both "column_3" and nothing in the third position does not end up with two columns of one name.
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 ¶
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 QuoteFields ¶ added in v0.49.0
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 ¶
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 SentinelFor ¶ added in v0.57.0
SentinelFor is the sentinel a read failure of this kind carries. Every kind has one, and TestEverySentinelIsAKindOfItsOwn holds this to that: a kind added later falls to ErrParsing here, which is a defensible answer and not necessarily the right one, so the test asks for the right one to be written.
func ValidateColumnCount ¶ added in v0.52.0
ValidateColumnCount reports a header wider than a table can hold. It is separate from the names because LTSV builds its header out of the labels its records carry rather than out of a header row, and the two arrive at the same CREATE TABLE.
func ValidateColumnNames ¶
ValidateColumnNames reports a header this backend cannot hold: one wider than MaxColumns, or one that names a 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 ¶
NewCSVReader returns a reader over the comma-separated records in r.
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 ¶
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.
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) IsText ¶ added in v0.55.0
IsText reports whether a format's bytes are text, which decides two things a caller has to get right before reading: a leading byte-order mark belongs to the encoding rather than to the first column name, and what follows has to be UTF-8. A container carries its own framing and is read as bytes, so putting a text decoder in front of one would refuse every file.
It lives on the format rather than in each caller because both doors into this module -- the loader and parser.Parse -- convert their own file type to a Format before reading, and two copies of this list would be one rule with two answers.
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 ParquetRenderer ¶ added in v0.53.0
type ParquetRenderer struct {
// contains filtered or unexported fields
}
ParquetRenderer renders values of one field the way a load of that field renders them.
A save writing a Parquet file back to itself checks its work against this: the text it starts from came out of a load, so a value it rebuilds from that text has to render as the same text again.
It is built once per field rather than once per value: what a field renders as follows from its type alone, and a field of a million values would otherwise answer the same question a million times.
func NewParquetRenderer ¶ added in v0.53.0
func NewParquetRenderer(node parquet.Node) (renderer ParquetRenderer, ok bool)
NewParquetRenderer reads what a field renders as, reporting false for a field it cannot render: a group, a repeated field, or one whose metadata is inconsistent enough that asking its type panics.
type Reconcile ¶
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 ¶
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 SheetLayout ¶ added in v0.53.0
type SheetLayout struct {
// HeaderRow is zero for a sheet holding no table.
HeaderRow int
RecordRows []int
}
SheetLayout is where on a sheet the table this package reads from it sits: the sheet's own number for the row the header came from, and for the row each record came from, in the order the records are read.
A save writing that table back needs it. The rows a table is made of are not the rows from the top of the sheet whenever the sheet holds a row with no cell in it, so a save that writes the header at row 1 and the records under it lands every cell on a row belonging to a different record.
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 ¶
NewTSVReader returns a reader over the tab-separated records in r.
type Unlabeled ¶ added in v0.49.0
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 ¶
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) File ¶ added in v0.53.0
File is the open workbook itself, for a save writing onto the file it is replacing.
func (*Workbook) LayoutOf ¶ added in v0.53.0
func (w *Workbook) LayoutOf(name string, rows [][]string) SheetLayout
LayoutOf answers where on a sheet the table sits, given the rows the library returned for that sheet. It takes them rather than reading them because reading a sheet is the expensive part of a save, and the caller that asks this has read it already.
func (*Workbook) NormalizeCells ¶ added in v0.54.0
NormalizeCells rewrites the cells of a sheet whose drawing is not the value behind them, reading the sheet's own XML rather than asking the library cell by cell.
A numeric cell becomes the number the file stores, since a number format says how a spreadsheet paints a number and not what the number is, and a cell a date format draws becomes ISO 8601, which is the form the datetime inference recognizes. A number drawn as a time of day or an elapsed duration keeps its drawing, and so does everything that does not store a number.
The two ways of reaching a cell's style agree on all of that; they differ in what finding out costs. Asking the library makes it unmarshal the whole worksheet into its object model, which for an 18.5 MB workbook of 200,000 rows is 1470 MB on top of the 267 MB the rows themselves cost. Reading the XML costs what the rewritten cells cost. The asking way is what this falls back to when the workbook arrived without its bytes or its parts do not say where the sheet is -- a sheet missing its dates would be worse than a slow one.
func (*Workbook) ReadSheet ¶
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) Rows ¶ added in v0.59.0
Rows returns the cells of one sheet as the library draws them.
A panic inside the library is returned as a parse error. The library checks a cell's shared-string index against the table it holds in memory, but a table larger than its in-memory limit is spilled to a temporary file and looked up there with only the upper bound checked, so a cell pointing at string -1 was an index out of range (GO-2026-6452). The workbook is input anyone can hand over, and a malformed one is a file to refuse, not a reason for the program reading it to stop.
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.