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 LTSVLabelKey(label string) string
- func NoExcelSheetsError(f ExcelSheetSource, policy ExcelSheetPolicy) error
- func NormalizeLineEndings(reader io.Reader) io.Reader
- func NormalizeXLSXDates(f *excelize.File, sheet string, rows [][]string) [][]string
- func SQLiteFloatText(f float64, bitSize int) string
- func SelectExcelSheets(f ExcelSheetSource, policy ExcelSheetPolicy) (loaded, skipped []string, err 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 Reconcile
- type Rendering
- type Result
- type TSVReader
- type Workbook
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;
Variables ¶
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.
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 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 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.
func NormalizeXLSXDates ¶
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 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 ValidateColumnNames ¶
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 ¶
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 )
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
// 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
}
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 ¶
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 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 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) 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) 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.