Documentation ¶
Overview ¶
Package trdsql implements execute SQL queries on tabular data.
trdsql imports tabular data into a database, executes SQL queries, and executes exports.
Example ¶
package main import ( "fmt" "log" "os" "github.com/noborus/trdsql" ) func main() { in := []byte(`"Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" `) tmpfile, err := os.CreateTemp(os.TempDir(), "xxx") if err != nil { log.Print(err) return } defer func() { defer os.Remove(tmpfile.Name()) }() if _, err := tmpfile.Write(in); err != nil { log.Print(err) return } trd := trdsql.NewTRDSQL( trdsql.NewImporter(), trdsql.NewExporter(trdsql.NewWriter()), ) // #nosec G201 query := fmt.Sprintf("SELECT c1 FROM %s ORDER BY c1", tmpfile.Name()) if err := trd.Exec(query); err != nil { log.Print(err) return } }
Output: Ken Rob Robert
Example (Options) ¶
package main import ( "fmt" "log" "os" "github.com/noborus/trdsql" ) func main() { in := []byte(`first_name,last_name,username "Rob","Pike",rob Ken,Thompson,ken "Robert","Griesemer","gri" `) tmpfile, err := os.CreateTemp(os.TempDir(), "xxx") if err != nil { log.Print(err) return } defer func() { defer os.Remove(tmpfile.Name()) }() _, err = tmpfile.Write(in) if err != nil { log.Print(err) return } // NewImporter importer := trdsql.NewImporter( trdsql.InFormat(trdsql.CSV), trdsql.InHeader(true), ) // NewWriter & NewExporter writer := trdsql.NewWriter( trdsql.OutFormat(trdsql.JSON), ) exporter := trdsql.NewExporter(writer) trd := trdsql.NewTRDSQL(importer, exporter) // #nosec G201 query := fmt.Sprintf("SELECT * FROM %s ORDER BY username", tmpfile.Name()) err = trd.Exec(query) if err != nil { log.Print(err) return } }
Output: [ { "first_name": "Robert", "last_name": "Griesemer", "username": "gri" }, { "first_name": "Ken", "last_name": "Thompson", "username": "ken" }, { "first_name": "Rob", "last_name": "Pike", "username": "rob" } ]
Index ¶
- Constants
- Variables
- func Analyze(fileName string, opts *AnalyzeOpts, readOpts *ReadOpts) error
- func ConvertTypes(dbTypes []string) []string
- func EnableDebug()
- func EnableMultipleQueries()
- func ImportFile(db *DB, fileName string, readOpts *ReadOpts) (string, error)
- func ImportFileContext(ctx context.Context, db *DB, fileName string, readOpts *ReadOpts) (string, error)
- func RegisterReaderFunc(ext string, readerFunc ReaderFunc)
- func SQLFields(query string) []string
- func TableNames(parsedQuery []string) (map[string]string, []int)
- func ValString(v any) string
- type AnalyzeOpts
- type BufferImporter
- type CSVReader
- type CSVWriter
- type DB
- func (db *DB) CreateTable(tableName string, columnNames []string, columnTypes []string, isTemporary bool) error
- func (db *DB) CreateTableContext(ctx context.Context, tableName string, columnNames []string, ...) error
- func (db *DB) Disconnect() error
- func (db *DB) Import(tableName string, columnNames []string, reader Reader) error
- func (db *DB) ImportContext(ctx context.Context, tableName string, columnNames []string, reader Reader) error
- func (db *DB) OtherExecContext(ctx context.Context, query string) error
- func (db *DB) QuotedName(orgName string) string
- func (db *DB) Select(query string) (*sql.Rows, error)
- func (db *DB) SelectContext(ctx context.Context, query string) (*sql.Rows, error)
- type Exporter
- type Format
- type GWReader
- type Importer
- type JSONLWriter
- type JSONReader
- type JSONWriter
- type LTSVReader
- type LTSVWriter
- type RAWWriter
- type ReadFormat
- type ReadOpt
- func InDelimiter(d string) ReadOpt
- func InFormat(f Format) ReadOpt
- func InHeader(h bool) ReadOpt
- func InJQ(p string) ReadOpt
- func InLimitRead(p bool) ReadOpt
- func InNULL(s string) ReadOpt
- func InNeedNULL(n bool) ReadOpt
- func InPreRead(p int) ReadOpt
- func InRowNumber(t bool) ReadOpt
- func InSkip(s int) ReadOpt
- func IsTemporary(t bool) ReadOpt
- type ReadOpts
- type Reader
- type ReaderFunc
- type SliceImporter
- type SliceReader
- type SliceWriter
- type TBLNRead
- type TBLNWriter
- type TRDSQL
- type TWWriter
- type TextReader
- type VFWriter
- type WriteFormat
- type WriteOpt
- func ErrStream(w io.Writer) WriteOpt
- func OutAllQuotes(a bool) WriteOpt
- func OutDelimiter(d string) WriteOpt
- func OutFormat(f Format) WriteOpt
- func OutHeader(h bool) WriteOpt
- func OutNULL(s string) WriteOpt
- func OutNeedNULL(n bool) WriteOpt
- func OutNoWrap(w bool) WriteOpt
- func OutQuote(q string) WriteOpt
- func OutStream(w io.Writer) WriteOpt
- func OutUseCRLF(c bool) WriteOpt
- type WriteOpts
- type Writer
- type YAMLReader
- type YAMLWriter
Examples ¶
Constants ¶
const DefaultDBType = "text"
DefaultDBType is default type.
Variables ¶
var ( // ErrNoTransaction is returned if SQL is executed when a transaction has not started. // SQL must be executed within a transaction. ErrNoTransaction = errors.New("transaction has not been started") // ErrNilReader is returned by Set reader of the specified file is nil error. ErrNilReader = errors.New("nil reader") // ErrInvalidNames is returned by Set if invalid names(number of columns is 0). ErrInvalidNames = errors.New("invalid names") // ErrInvalidTypes is returned by Set if invalid column types (does not match the number of column names). ErrInvalidTypes = errors.New("invalid types") // ErrNoStatement is returned by no SQL statement. ErrNoStatement = errors.New("no SQL statement") )
var ( // ErrInvalidColumn is returned if invalid column. ErrInvalidColumn = errors.New("invalid column") // ErrNoReader is returned when there is no reader. ErrNoReader = errors.New("no reader") // ErrUnknownFormat is returned if the format is unknown. ErrUnknownFormat = errors.New("unknown format") // ErrNoRows returned when there are no rows. ErrNoRows = errors.New("no rows") // ErrUnableConvert is returned if it cannot be converted to a table. ErrUnableConvert = errors.New("unable to convert") // ErrNoMatchFound is returned if no match is found. ErrNoMatchFound = errors.New("no match found") // ErrNonDefinition is returned when there is no definition. ErrNonDefinition = errors.New("no definition") // ErrInvalidJSON is returned when the JSON is invalid. ErrInvalidJSON = errors.New("invalid JSON") // ErrInvalidYAML is returned when the YAML is invalid. ErrInvalidYAML = errors.New("invalid YAML") )
var AppName = "trdsql"
AppName is used for command names.
var DefaultDriver = "sqlite3"
var Version = `devel`
Version is trdsql version.
Functions ¶
func Analyze ¶ added in v0.7.2
func Analyze(fileName string, opts *AnalyzeOpts, readOpts *ReadOpts) error
Analyze analyzes the file and outputs the table information. In addition, SQL execution examples are output.
func ConvertTypes ¶ added in v0.6.0
ConvertTypes is converts database types to common types.
func EnableDebug ¶ added in v0.6.0
func EnableDebug()
EnableDebug is enable verbose output for debug.
func EnableMultipleQueries ¶ added in v0.20.0
func EnableMultipleQueries()
EnableMultipleQueries enables multiple queries.
func ImportFile ¶ added in v0.6.0
ImportFile is imports a file. Return the quoted table name and error. Do not import if file not found (no error). Wildcards can be passed as fileName.
func ImportFileContext ¶ added in v0.7.9
func ImportFileContext(ctx context.Context, db *DB, fileName string, readOpts *ReadOpts) (string, error)
ImportFileContext is imports a file. Return the quoted table name and error. Do not import if file not found (no error). Wildcards can be passed as fileName.
func RegisterReaderFunc ¶ added in v0.13.0
func RegisterReaderFunc(ext string, readerFunc ReaderFunc)
func SQLFields ¶ added in v0.7.0
SQLFields returns an array of string fields (interpreting quotes) from the argument query.
func TableNames ¶ added in v0.6.3
TableNames returns a map of table names that may be tables by a simple SQL parser from the query string of the argument, along with the locations within the parsed query where those table names were found.
Types ¶
type AnalyzeOpts ¶ added in v0.7.2
type AnalyzeOpts struct { // Command is string of the execution command. Command string // Quote is the quote character(s) that varies depending on the sql driver. Quote string // Detail is outputs detailed information. Detail bool // OutStream is the output destination. OutStream io.Writer }
AnalyzeOpts represents the options for the operation of Analyze.
func NewAnalyzeOpts ¶ added in v0.7.2
func NewAnalyzeOpts() *AnalyzeOpts
NewAnalyzeOpts returns AnalyzeOpts.
type BufferImporter ¶ added in v0.6.0
type BufferImporter struct { Reader // contains filtered or unexported fields }
BufferImporter a structure that includes tableName and Reader.
Example ¶
package main import ( "bytes" "log" "github.com/noborus/trdsql" ) func main() { jsonString := ` [ { "name": "Sarah Carpenter", "gender": "female", "company": "ACCUSAGE", "tags": [ "veniam", "exercitation", "nulla", "anim", "ea", "ullamco", "ut" ], "greeting": "Hello, Sarah Carpenter! You have 1 unread messages." }, { "name": "Perez Atkinson", "gender": "male", "company": "JOVIOLD", "tags": [ "minim", "adipisicing", "ad", "occaecat", "incididunt", "eu", "esse" ], "greeting": "Hello, Perez Atkinson! You have 10 unread messages." }, { "name": "Valeria Potts", "gender": "female", "company": "EXOZENT", "tags": [ "esse", "pariatur", "nisi", "commodo", "adipisicing", "ut", "consectetur" ], "greeting": "Hello, Valeria Potts! You have 8 unread messages." } ] ` r := bytes.NewBufferString(jsonString) importer, err := trdsql.NewBufferImporter("test", r, trdsql.InFormat(trdsql.JSON)) if err != nil { log.Print(err) return } writer := trdsql.NewWriter( trdsql.OutFormat(trdsql.CSV), trdsql.OutDelimiter("\t"), ) trd := trdsql.NewTRDSQL(importer, trdsql.NewExporter(writer)) err = trd.Exec("SELECT name,gender,company FROM test") if err != nil { log.Print(err) return } }
Output: Sarah Carpenter female ACCUSAGE Perez Atkinson male JOVIOLD Valeria Potts female EXOZENT
func NewBufferImporter ¶ added in v0.6.0
NewBufferImporter returns trdsql BufferImporter.
func (*BufferImporter) Import ¶ added in v0.6.0
func (i *BufferImporter) Import(db *DB, query string) (string, error)
Import is a method to import from Reader in BufferImporter.
func (*BufferImporter) ImportContext ¶ added in v0.7.9
ImportContext is a method to import from Reader in BufferImporter.
type CSVReader ¶ added in v0.6.0
type CSVReader struct {
// contains filtered or unexported fields
}
CSVReader provides methods of the Reader interface.
func NewCSVReader ¶ added in v0.6.0
NewCSVReader returns CSVReader and error.
func NewPSVReader ¶ added in v0.13.0
func NewTSVReader ¶ added in v0.13.0
func (*CSVReader) PreReadRow ¶ added in v0.6.0
PreReadRow is returns only columns that store preread rows.
type CSVWriter ¶ added in v0.6.0
type CSVWriter struct {
// contains filtered or unexported fields
}
CSVWriter provides methods of the Writer interface.
func NewCSVWriter ¶ added in v0.6.0
NewCSVWriter returns CSVWriter.
type DB ¶ added in v0.6.0
type DB struct { // *sql.DB represents the database connection. *sql.DB // Tx represents a database transaction. Tx *sql.Tx // contains filtered or unexported fields }
DB represents database information.
func Connect ¶
Connect is connects to the database. Currently supported drivers are sqlite3, mysql, postgres. Set quote character and maxBulk depending on the driver type.
func (*DB) CreateTable ¶ added in v0.6.0
func (db *DB) CreateTable(tableName string, columnNames []string, columnTypes []string, isTemporary bool) error
CreateTable is create a (temporary) table in the database. The arguments are the table name, column name, column type, and temporary flag.
func (*DB) CreateTableContext ¶ added in v0.7.9
func (db *DB) CreateTableContext(ctx context.Context, tableName string, columnNames []string, columnTypes []string, isTemporary bool) error
CreateTableContext is create a (temporary) table in the database. The arguments are the table name, column name, column type, and temporary flag.
func (*DB) Disconnect ¶ added in v0.6.0
Disconnect is disconnect the database.
func (*DB) ImportContext ¶ added in v0.7.9
func (db *DB) ImportContext(ctx context.Context, tableName string, columnNames []string, reader Reader) error
ImportContext is imports data into a table.
func (*DB) OtherExecContext ¶ added in v0.20.0
func (*DB) QuotedName ¶ added in v0.7.0
QuotedName returns the table name quoted. Returns as is, if already quoted.
type Exporter ¶ added in v0.6.0
type Exporter interface { Export(db *DB, sql string) error ExportContext(ctx context.Context, db *DB, sql string) error }
Exporter is the interface for processing query results. Exporter executes SQL and outputs to Writer.
type Format ¶ added in v0.6.0
type Format int
Format represents the import/export format.
const ( // import (guesses for import format). GUESS Format = iota // import/export // Format using go standard CSV library. CSV // import/export // Labeled Tab-separated Values. LTSV // import/export // Format using go standard JSON library. JSON // import/export // TBLN format(https://tbln.dev). TBLN // import // Format using guesswidth library. WIDTH // import TEXT // export // Output as it is. // Multiple characters can be selected as delimiter. RAW // export // MarkDown format. MD // export // ASCII Table format. AT // export // Vertical format. VF // export // JSON Lines format(http://jsonlines.org/). JSONL // import/export // YAML format. YAML // import // Tab-Separated Values format. Format using go standard CSV library. TSV // import // Pipe-Separated Values format. Format using go standard CSV library. PSV )
Represents Format.
func OutputFormat ¶ added in v0.13.0
OutputFormat returns the format from the extension.
type GWReader ¶ added in v0.11.0
type GWReader struct {
// contains filtered or unexported fields
}
GWReader provides methods of the Reader interface.
func NewGWReader ¶ added in v0.11.0
NewGWReader returns GWReader and error.
func (*GWReader) PreReadRow ¶ added in v0.11.0
PreReadRow is returns only columns that store preread rows.
type Importer ¶ added in v0.6.0
type Importer interface { Import(db *DB, query string) (string, error) ImportContext(ctx context.Context, db *DB, query string) (string, error) }
Importer is the interface import data into the database. Importer parses sql query to decide which file to Import. Therefore, the reader does not receive it directly.
type JSONLWriter ¶ added in v0.7.3
type JSONLWriter struct {
// contains filtered or unexported fields
}
JSONLWriter provides methods of the Writer interface.
func NewJSONLWriter ¶ added in v0.7.3
func NewJSONLWriter(writeOpts *WriteOpts) *JSONLWriter
NewJSONLWriter returns JSONLWriter.
func (*JSONLWriter) PostWrite ¶ added in v0.7.3
func (w *JSONLWriter) PostWrite() error
PostWrite does nothing.
type JSONReader ¶ added in v0.6.0
type JSONReader struct {
// contains filtered or unexported fields
}
JSONReader provides methods of the Reader interface.
func NewJSONReader ¶ added in v0.6.0
func NewJSONReader(reader io.Reader, opts *ReadOpts) (*JSONReader, error)
NewJSONReader returns JSONReader and error.
func (*JSONReader) Names ¶ added in v0.6.0
func (r *JSONReader) Names() ([]string, error)
Names returns column names.
func (*JSONReader) PreReadRow ¶ added in v0.6.0
func (r *JSONReader) PreReadRow() [][]any
PreReadRow is returns only columns that store preRead rows. One json (not jsonl) returns all rows with preRead.
func (*JSONReader) ReadRow ¶ added in v0.6.0
func (r *JSONReader) ReadRow(row []any) ([]any, error)
ReadRow is read the rest of the row. Only jsonl requires ReadRow in json.
func (*JSONReader) Types ¶ added in v0.6.0
func (r *JSONReader) Types() ([]string, error)
Types returns column types. All JSON types return the DefaultDBType.
type JSONWriter ¶ added in v0.6.0
type JSONWriter struct {
// contains filtered or unexported fields
}
JSONWriter provides methods of the Writer interface.
func NewJSONWriter ¶ added in v0.6.0
func NewJSONWriter(writeOpts *WriteOpts) *JSONWriter
NewJSONWriter returns JSONWriter.
func (*JSONWriter) PostWrite ¶ added in v0.6.0
func (w *JSONWriter) PostWrite() error
PostWrite is actual output.
type LTSVReader ¶ added in v0.6.0
type LTSVReader struct {
// contains filtered or unexported fields
}
LTSVReader provides methods of the Reader interface.
func NewLTSVReader ¶ added in v0.6.0
func NewLTSVReader(reader io.Reader, opts *ReadOpts) (*LTSVReader, error)
NewLTSVReader returns LTSVReader and error.
func (*LTSVReader) Names ¶ added in v0.6.0
func (r *LTSVReader) Names() ([]string, error)
Names returns column names.
func (*LTSVReader) PreReadRow ¶ added in v0.6.0
func (r *LTSVReader) PreReadRow() [][]any
PreReadRow is returns only columns that store preread rows.
func (*LTSVReader) ReadRow ¶ added in v0.6.0
func (r *LTSVReader) ReadRow(row []any) ([]any, error)
ReadRow is read the rest of the row.
func (*LTSVReader) Types ¶ added in v0.6.0
func (r *LTSVReader) Types() ([]string, error)
Types returns column types. All LTSV types return the DefaultDBType.
type LTSVWriter ¶ added in v0.6.0
type LTSVWriter struct {
// contains filtered or unexported fields
}
LTSVWriter provides methods of the Writer interface.
func NewLTSVWriter ¶ added in v0.6.0
func NewLTSVWriter(writeOpts *WriteOpts) *LTSVWriter
NewLTSVWriter returns LTSVWriter.
func (*LTSVWriter) PostWrite ¶ added in v0.6.0
func (w *LTSVWriter) PostWrite() error
PostWrite is flush.
type RAWWriter ¶ added in v0.6.0
type RAWWriter struct {
// contains filtered or unexported fields
}
RAWWriter provides methods of the Writer interface.
func NewRAWWriter ¶ added in v0.6.0
NewRAWWriter returns RAWWriter.
type ReadFormat ¶ added in v0.6.0
type ReadFormat struct {
*ReadOpts
}
ReadFormat represents a structure that satisfies the Importer.
func NewImporter ¶ added in v0.6.0
func NewImporter(options ...ReadOpt) *ReadFormat
NewImporter returns trdsql default Importer. The argument is an option of Functional Option Pattern.
usage:
trdsql.NewImporter( trdsql.InFormat(trdsql.CSV), trdsql.InHeader(true), trdsql.InDelimiter(";"), )
func (*ReadFormat) Import ¶ added in v0.6.0
func (i *ReadFormat) Import(db *DB, query string) (string, error)
Import is parses the SQL statement and imports one or more tables. Import is called from Exec. Return the rewritten SQL and error. No error is returned if there is no table to import.
func (*ReadFormat) ImportContext ¶ added in v0.7.9
ImportContext is parses the SQL statement and imports one or more tables. ImportContext is called from ExecContext. Return the rewritten SQL and error. No error is returned if there is no table to import.
type ReadOpt ¶ added in v0.6.0
type ReadOpt func(*ReadOpts)
ReadOpt returns a *ReadOpts structure. Used when calling NewImporter.
func InDelimiter ¶ added in v0.6.0
InDelimiter is the field delimiter.
func InLimitRead ¶ added in v0.9.1
func InNeedNULL ¶ added in v0.10.0
InNeedNULL sets a flag as to whether it should be replaced with NULL.
func InRowNumber ¶ added in v1.1.0
func IsTemporary ¶ added in v0.6.0
IsTemporary is a flag whether to make temporary table.
type ReadOpts ¶ added in v0.6.0
type ReadOpts struct { // InDelimiter is the field delimiter. // default is ',' InDelimiter string // InNULL is a string to replace with NULL. InNULL string // InJQuery is a jq expression. InJQuery string // InFormat is read format. // The supported format is CSV/LTSV/JSON/TBLN. InFormat Format // InPreRead is number of rows to read ahead. // CSV/LTSV reads the specified number of rows to // determine the number of columns. InPreRead int // InSkip is number of rows to skip. // Skip reading specified number of lines. InSkip int // InLimitRead is limit read. InLimitRead bool // InHeader is true if there is a header. // It is used as a column name. InHeader bool // InNeedNULL is true, replace InNULL with NULL. InNeedNULL bool // IsTemporary is a flag whether to make temporary table. // default is true. IsTemporary bool // InRowNumber is row number. InRowNumber bool // contains filtered or unexported fields }
ReadOpts represents options that determine the behavior of the reader.
func NewReadOpts ¶ added in v0.6.0
NewReadOpts Returns ReadOpts.
type Reader ¶ added in v0.6.0
type Reader interface { // Names returns column names. Names() ([]string, error) // Types returns column types. Types() ([]string, error) // PreReadRow is returns only columns that store preRead rows. PreReadRow() [][]any // ReadRow is read the rest of the row. ReadRow(row []any) ([]any, error) }
Reader is wrap the reader. Reader reads from tabular files.
type ReaderFunc ¶ added in v0.13.0
ReaderFunc is a function that creates a new Reader.
type SliceImporter ¶ added in v0.6.0
type SliceImporter struct {
*SliceReader
}
SliceImporter is a structure that includes SliceReader. SliceImporter can be used as a library from another program. It is not used from the command. SliceImporter is an importer that reads one slice data.
Example ¶
package main import ( "log" "github.com/noborus/trdsql" ) func main() { data := []struct { id int name string }{ {id: 1, name: "Bod"}, {id: 2, name: "Alice"}, {id: 3, name: "Henry"}, } tableName := "slice" importer := trdsql.NewSliceImporter(tableName, data) trd := trdsql.NewTRDSQL(importer, trdsql.NewExporter(trdsql.NewWriter())) err := trd.Exec("SELECT name,id FROM slice ORDER BY id DESC") if err != nil { log.Print(err) return } }
Output: Henry,3 Alice,2 Bod,1
func NewSliceImporter ¶ added in v0.6.0
func NewSliceImporter(tableName string, data any) *SliceImporter
NewSliceImporter returns trdsql SliceImporter.
func (*SliceImporter) Import ¶ added in v0.6.0
func (i *SliceImporter) Import(db *DB, query string) (string, error)
Import is a method to import from SliceReader in SliceImporter.
func (*SliceImporter) ImportContext ¶ added in v0.7.9
ImportContext is a method to import from SliceReader in SliceImporter.
type SliceReader ¶ added in v0.6.0
type SliceReader struct {
// contains filtered or unexported fields
}
SliceReader is a structure for reading tabular data in memory. It can be used as the trdsql reader interface.
func NewSliceReader ¶ added in v0.6.0
func NewSliceReader(tableName string, args any) *SliceReader
NewSliceReader takes a tableName and tabular data in memory and returns SliceReader. The tabular data that can be received is a one-dimensional array, a two-dimensional array, a map, and an array of structures.
func (*SliceReader) Names ¶ added in v0.6.0
func (r *SliceReader) Names() ([]string, error)
Names returns column names.
func (*SliceReader) PreReadRow ¶ added in v0.6.0
func (r *SliceReader) PreReadRow() [][]any
PreReadRow is returns entity of the data.
func (*SliceReader) ReadRow ¶ added in v0.6.0
func (r *SliceReader) ReadRow(row []any) ([]any, error)
ReadRow only returns EOF.
func (*SliceReader) TableName ¶ added in v0.6.3
func (r *SliceReader) TableName() (string, error)
TableName returns Table name.
func (*SliceReader) Types ¶ added in v0.6.0
func (r *SliceReader) Types() ([]string, error)
Types returns column types.
type SliceWriter ¶ added in v0.6.0
type SliceWriter struct {
Table [][]any
}
SliceWriter is a structure to receive the result in slice.
Example ¶
package main import ( "fmt" "log" "github.com/noborus/trdsql" ) func main() { data := []struct { id int name string }{ {id: 1, name: "Bod"}, {id: 2, name: "Alice"}, {id: 3, name: "Henry"}, } tableName := "slice" importer := trdsql.NewSliceImporter(tableName, data) writer := trdsql.NewSliceWriter() trd := trdsql.NewTRDSQL(importer, trdsql.NewExporter(writer)) err := trd.Exec("SELECT name,id FROM slice ORDER BY id DESC") if err != nil { log.Print(err) return } table := writer.Table fmt.Print(table) }
Output: [[Henry 3] [Alice 2] [Bod 1]]
func NewSliceWriter ¶ added in v0.6.0
func NewSliceWriter() *SliceWriter
NewSliceWriter return SliceWriter.
func (*SliceWriter) PostWrite ¶ added in v0.6.0
func (w *SliceWriter) PostWrite() error
PostWrite does nothing.
type TBLNRead ¶ added in v0.6.0
type TBLNRead struct {
// contains filtered or unexported fields
}
TBLNRead provides methods of the Reader interface.
func NewTBLNReader ¶ added in v0.6.0
NewTBLNReader returns TBLNRead and error.
func (*TBLNRead) PreReadRow ¶ added in v0.6.0
PreReadRow is returns only columns that store preread rows.
type TBLNWriter ¶ added in v0.6.0
type TBLNWriter struct {
// contains filtered or unexported fields
}
TBLNWriter provides methods of the Writer interface.
func NewTBLNWriter ¶ added in v0.6.0
func NewTBLNWriter(writeOpts *WriteOpts) *TBLNWriter
NewTBLNWriter returns TBLNWriter.
func (*TBLNWriter) PostWrite ¶ added in v0.6.0
func (w *TBLNWriter) PostWrite() error
PostWrite is nil.
type TRDSQL ¶
type TRDSQL struct { // Importer is interface of processing to // import(create/insert) data. Importer Importer // Exporter is interface export to the process of // export(select) from the database. Exporter Exporter // Driver is database driver name(sqlite3/sqlite/mysql/postgres). Driver string // Dsn is data source name. Dsn string }
TRDSQL represents DB definition and Importer/Exporter interface.
type TWWriter ¶ added in v0.6.0
type TWWriter struct {
// contains filtered or unexported fields
}
TWWriter provides methods of the Writer interface.
func NewTWWriter ¶ added in v0.6.0
NewTWWriter returns TWWriter.
type TextReader ¶ added in v1.1.0
type TextReader struct {
// contains filtered or unexported fields
}
TextReader provides a reader for text format.
func NewTextReader ¶ added in v1.1.0
func NewTextReader(reader io.Reader, opts *ReadOpts) (*TextReader, error)
NewTextReader returns a new TextReader.
func (*TextReader) Names ¶ added in v1.1.0
func (r *TextReader) Names() ([]string, error)
Names returns column names.
func (*TextReader) PreReadRow ¶ added in v1.1.0
func (r *TextReader) PreReadRow() [][]any
PreReadRow returns pre-read rows.
func (*TextReader) ReadRow ¶ added in v1.1.0
func (r *TextReader) ReadRow([]any) ([]any, error)
ReadRow reads a row.
func (*TextReader) Types ¶ added in v1.1.0
func (r *TextReader) Types() ([]string, error)
Types returns column types.
type VFWriter ¶ added in v0.6.0
type VFWriter struct {
// contains filtered or unexported fields
}
VFWriter is Vertical Format output.
func NewVFWriter ¶ added in v0.6.0
NewVFWriter returns VFWriter.
type WriteFormat ¶ added in v0.6.0
type WriteFormat struct { Writer // contains filtered or unexported fields }
WriteFormat represents a structure that satisfies Exporter.
func NewExporter ¶ added in v0.6.0
func NewExporter(writer Writer) *WriteFormat
NewExporter returns trdsql default Exporter.
func (*WriteFormat) Export ¶ added in v0.6.0
func (e *WriteFormat) Export(db *DB, sql string) error
Export is execute SQL(Select) and the result is written out by the writer. Export is called from Exec.
func (*WriteFormat) ExportContext ¶ added in v0.7.9
ExportContext is execute SQL(Select) and the result is written out by the writer. ExportContext is called from ExecContext.
type WriteOpt ¶ added in v0.6.0
type WriteOpt func(*WriteOpts)
WriteOpt is a function to set WriteOpts.
func OutAllQuotes ¶ added in v0.7.4
OutAllQuotes sets all quotes.
func OutDelimiter ¶ added in v0.6.0
OutDelimiter sets delimiter.
func OutNeedNULL ¶ added in v0.10.0
OutNeedNULL sets a flag to replace NULL.
type WriteOpts ¶ added in v0.6.0
type WriteOpts struct { // OutStream is the output destination. OutStream io.Writer // ErrStream is the error output destination. ErrStream io.Writer // OutDelimiter is the output delimiter (Use only CSV and Raw). OutDelimiter string // OutQuote is the output quote character (Use only CSV). OutQuote string // OutNeedNULL is true, replace NULL with OutNULL. OutNULL string // OutFormat is the writing format. OutFormat Format // OutAllQuotes is true if Enclose all fields (Use only CSV). OutAllQuotes bool // True to use \r\n as the line terminator (Use only CSV). OutUseCRLF bool // OutHeader is true if it outputs a header(Use only CSV and Raw). OutHeader bool // OutNoWrap is true, do not wrap long columns(Use only AT and MD). OutNoWrap bool // OutNeedNULL is true, replace NULL with OutNULL. OutNeedNULL bool // OutJSONToYAML is true, convert JSON to YAML(Use only YAML). OutJSONToYAML bool }
WriteOpts represents options that determine the behavior of the writer.
type Writer ¶ added in v0.6.0
type Writer interface { // PreWrite is called first to write. // The arguments are a list of column names and a list of type names. PreWrite(columns []string, types []string) error // WriteRow is row write. WriteRow(row []any, columns []string) error // PostWrite is called last in the write. PostWrite() error }
Writer is an interface that wraps the Write method that writes from the database to a file. Writer is a group of methods called from Export.
type YAMLReader ¶ added in v0.12.0
type YAMLReader struct {
// contains filtered or unexported fields
}
YAMLReader provides methods of the Reader interface.
func NewYAMLReader ¶ added in v0.12.0
func NewYAMLReader(reader io.Reader, opts *ReadOpts) (*YAMLReader, error)
NewYAMLReader returns YAMLReader and error.
func (*YAMLReader) Names ¶ added in v0.12.0
func (r *YAMLReader) Names() ([]string, error)
Names returns column names.
func (*YAMLReader) PreReadRow ¶ added in v0.12.0
func (r *YAMLReader) PreReadRow() [][]any
PreReadRow is returns only columns that store preRead rows. One YAML (not YAMLl) returns all rows with preRead.
func (*YAMLReader) ReadRow ¶ added in v0.12.0
func (r *YAMLReader) ReadRow(row []any) ([]any, error)
ReadRow is read the rest of the row. Only YAMLl requires ReadRow in YAML.
func (*YAMLReader) Types ¶ added in v0.12.0
func (r *YAMLReader) Types() ([]string, error)
Types returns column types. All YAML types return the DefaultDBType.
type YAMLWriter ¶ added in v0.12.0
type YAMLWriter struct {
// contains filtered or unexported fields
}
YAMLWriter provides methods of the Writer interface.
func NewYAMLWriter ¶ added in v0.12.0
func NewYAMLWriter(writeOpts *WriteOpts) *YAMLWriter
NewYAMLWriter returns YAMLWriter.
func (*YAMLWriter) PostWrite ¶ added in v0.12.0
func (w *YAMLWriter) PostWrite() error
PostWrite is actual output.
Source Files ¶
- analyze.go
- database.go
- database_connect_cgo.go
- debug.go
- exporter.go
- importer.go
- importer_buffer.go
- importer_slice.go
- input_csv.go
- input_gw.go
- input_json.go
- input_ltsv.go
- input_row_number.go
- input_slice.go
- input_tbln.go
- input_text.go
- input_yaml.go
- keywords.go
- output_csv.go
- output_json.go
- output_jsonl.go
- output_ltsv.go
- output_raw.go
- output_slice.go
- output_tablewriter.go
- output_tbln.go
- output_vertical.go
- output_yaml.go
- reader.go
- strings.go
- trdsql.go
- version.go
- writer.go
Directories ¶
Path | Synopsis |
---|---|
_example
|
|
buffer
buffer is an example using NewBufferImporter.
|
buffer is an example using NewBufferImporter. |
import
import is an example of using a customized import.
|
import is an example of using a customized import. |
quotecsv
quotecsv is an example of outputting a column quoted in double quotes.
|
quotecsv is an example of outputting a column quoted in double quotes. |
simple
simple is an example of using trdsql as a library.
|
simple is an example of using trdsql as a library. |
slice
slice is to import data using NewSliceImporter.
|
slice is to import data using NewSliceImporter. |
writer
writer is an example of using a customized writer.
|
writer is an example of using a customized writer. |