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"
"io/ioutil"
"log"
"os"
"github.com/noborus/trdsql"
)
func main() {
in := []byte(`"Rob","Pike",rob
Ken,Thompson,ken
"Robert","Griesemer","gri"
`)
tmpfile, err := ioutil.TempFile("/tmp", "xxx")
if err != nil {
log.Fatal(err)
}
defer func() {
defer os.Remove(tmpfile.Name())
}()
_, err = tmpfile.Write(in)
if err != nil {
log.Fatal(err)
}
trd := trdsql.NewTRDSQL(
trdsql.NewImporter(),
trdsql.NewExporter(trdsql.NewWriter()),
)
query := fmt.Sprintf("SELECT c1 FROM %s ORDER BY c1", tmpfile.Name())
err = trd.Exec(query)
if err != nil {
log.Fatal(err)
}
}
Output: Ken Rob Robert
Example (Options) ¶
package main
import (
"fmt"
"io/ioutil"
"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 := ioutil.TempFile("/tmp", "xxx")
if err != nil {
log.Fatal(err)
}
defer func() {
defer os.Remove(tmpfile.Name())
}()
_, err = tmpfile.Write(in)
if err != nil {
log.Fatal(err)
}
// 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)
query := fmt.Sprintf("SELECT * FROM %s ORDER BY username", tmpfile.Name())
err = trd.Exec(query)
if err != nil {
log.Fatal(err)
}
}
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
- func ConvertTypes(dbTypes []string) []string
- func EnableDebug()
- func ImportFile(db *DB, fileName string, readOpts *ReadOpts) (string, error)
- func TableNames(query string) []string
- func ValString(v interface{}) string
- type BufferImporter
- type CSVReader
- type CSVWriter
- type DB
- func (db *DB) CreateTable(tableName string, names []string, types []string, isTemporary bool) error
- func (db *DB) Disconnect() error
- func (db *DB) EscapeName(oldName string) string
- func (db *DB) Import(tableName string, columnNames []string, reader Reader) error
- func (db *DB) RewriteSQL(query string, oldName string, newName string) (rewrite string)
- func (db *DB) Select(query string) (*sql.Rows, error)
- type Exporter
- type Format
- type Importer
- type JSONReader
- type JSONWriter
- type LTSVReader
- type LTSVWriter
- type RAWWriter
- type ReadFormat
- type ReadOpt
- type ReadOpts
- type Reader
- type SliceImporter
- type SliceReader
- type SliceWriter
- type TBLNRead
- type TBLNWriter
- type TRDSQL
- type TWWriter
- type Table
- type VFWriter
- type WriteFormat
- type WriteOpt
- type WriteOpts
- type Writer
Examples ¶
Constants ¶
const DefaultDBType = "text"
DefaultDBType is default type.
const VERSION = `0.6.3`
VERSION is trdsql version
Variables ¶
This section is empty.
Functions ¶
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 ImportFile ¶ added in v0.6.0
ImportFile is imports a file. Return the escaped table name and error. Do not import if file not found (no error). Wildcards can be passed as fileName.
func TableNames ¶ added in v0.6.3
TableNames returns slices of table names that may be tables by a simple SQL parser from the query string of the argument.
Types ¶
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.Fatal(err)
}
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.Fatal(err)
}
}
Output: Sarah Carpenter female ACCUSAGE Perez Atkinson male JOVIOLD Valeria Potts female EXOZENT
func NewBufferImporter ¶ added in v0.6.0
NewBufferImporter returns trdsql 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 (*CSVReader) PreReadRow ¶ added in v0.6.0
func (r *CSVReader) PreReadRow() [][]interface{}
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
DB is *sql.DB wrapper.
func (*DB) CreateTable ¶ added in v0.6.0
CreateTable is create a temporary table
func (*DB) Disconnect ¶ added in v0.6.0
Disconnect is disconnect the database
func (*DB) EscapeName ¶ added in v0.6.0
EscapeName is escape table name.
func (*DB) RewriteSQL ¶ added in v0.6.0
RewriteSQL is rewrite SQL from file name to table name.
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 // 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 )
Represents Format
type Importer ¶ added in v0.6.0
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 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() [][]interface{}
PreReadRow is returns only columns that store preread rows.
func (*JSONReader) ReadRow ¶ added in v0.6.0
func (r *JSONReader) ReadRow(row []interface{}) ([]interface{}, error)
ReadRow is read the rest of the row.
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
func (*JSONWriter) PreWrite ¶ added in v0.6.0
func (w *JSONWriter) PreWrite(columns []string, types []string) error
PreWrite is area preparation.
func (*JSONWriter) WriteRow ¶ added in v0.6.0
func (w *JSONWriter) WriteRow(values []interface{}, columns []string) error
WriteRow is Addition to array.
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() [][]interface{}
PreReadRow is returns only columns that store preread rows.
func (*LTSVReader) ReadRow ¶ added in v0.6.0
func (r *LTSVReader) ReadRow(row []interface{}) ([]interface{}, 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.
func (*LTSVWriter) PreWrite ¶ added in v0.6.0
func (w *LTSVWriter) PreWrite(columns []string, types []string) error
PreWrite is area preparation.
func (*LTSVWriter) WriteRow ¶ added in v0.6.0
func (w *LTSVWriter) WriteRow(values []interface{}, columns []string) error
WriteRow is row write.
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 is a structure that includes ReadOpts, and is an implementation of the Importer interface.
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(";"),
)
type ReadOpt ¶ added in v0.6.0
type ReadOpt func(*ReadOpts)
ReadOpt returns a *ReadOpts structure. Used when calling NewImporter. NewImporter(InFormat(CSV),InPreRead(2))
func InDelimiter ¶ added in v0.6.0
InDelimiter is the field delimiter.
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 {
// InFormat is read format.
// The supported format is CSV/LTSV/JSON/TBLN.
InFormat Format
// InPreRead is number of lines to read ahead.
// CSV/LTSV reads the specified number of rows to
// determine the number of columns.
InPreRead int
// InSkip is number of lines to skip.
// Skip reading specified number of lines.
InSkip int
// InDelimiter is the field delimiter.
// default is ','
InDelimiter string
// InHeader is true if there is a header.
// It is used as a column name.
InHeader bool
// IsTemporary is a flag whether to make temporary table.
// default is true.
IsTemporary bool
// contains filtered or unexported fields
}
ReadOpts option to determine reader.
func NewReadOpts ¶ added in v0.6.0
NewReadOpts Returns ReadOpts.
type Reader ¶ added in v0.6.0
type Reader interface {
Names() ([]string, error)
Types() ([]string, error)
PreReadRow() [][]interface{}
ReadRow([]interface{}) ([]interface{}, error)
}
Reader is wrap the 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.Fatal(err)
}
}
Output: Henry,3 Alice,2 Bod,1
func NewSliceImporter ¶ added in v0.6.0
func NewSliceImporter(tableName string, data interface{}) *SliceImporter
NewSliceImporter returns trdsql 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 interface{}) *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() [][]interface{}
PreReadRow is returns entity of the data.
func (*SliceReader) ReadRow ¶ added in v0.6.0
func (r *SliceReader) ReadRow(row []interface{}) ([]interface{}, 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 [][]interface{}
}
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.Fatal(err)
}
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.
func (*SliceWriter) PreWrite ¶ added in v0.6.0
func (w *SliceWriter) PreWrite(columns []string, types []string) error
PreWrite prepares the area.
func (*SliceWriter) WriteRow ¶ added in v0.6.0
func (w *SliceWriter) WriteRow(values []interface{}, columns []string) error
WriteRow stores the result in Table.
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
func (r *TBLNRead) PreReadRow() [][]interface{}
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.
func (*TBLNWriter) PreWrite ¶ added in v0.6.0
func (w *TBLNWriter) PreWrite(columns []string, types []string) error
PreWrite is prepare tbln definition body.
func (*TBLNWriter) WriteRow ¶ added in v0.6.0
func (w *TBLNWriter) WriteRow(values []interface{}, columns []string) error
WriteRow is row write.
type TRDSQL ¶
type TRDSQL struct {
// Driver is database driver name(sqlite3/mysql/postgres).
Driver string
// Dsn is data source name.
Dsn string
// 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
}
TRDSQL structure is a structure that defines the whole operation.
type TWWriter ¶ added in v0.6.0
type TWWriter struct {
// contains filtered or unexported fields
}
TWWriter is tablewriter struct
func NewTWWriter ¶ added in v0.6.0
NewTWWriter returns TWWriter.
type Table ¶ added in v0.6.0
type Table struct {
// contains filtered or unexported fields
}
Table is import Table data
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
}
WriteFormat is a structure that includes Writer and WriteOpts, and is an implementation of the Exporter interface.
func NewExporter ¶ added in v0.6.0
func NewExporter(writer Writer) *WriteFormat
NewExporter returns trdsql default Exporter.
type WriteOpt ¶ added in v0.6.0
type WriteOpt func(*WriteOpts)
WriteOpt is a function to set WriteOpts.
func OutDelimiter ¶ added in v0.6.0
OutDelimiter sets delimiter.
type WriteOpts ¶ added in v0.6.0
type WriteOpts struct {
OutFormat Format
OutDelimiter string
OutHeader bool
OutStream io.Writer
ErrStream io.Writer
}
WriteOpts is the option to determine the writer process.
Source Files
¶
- database.go
- debug.go
- exporter.go
- importer.go
- importer_buffer.go
- importer_slice.go
- input_csv.go
- input_json.go
- input_ltsv.go
- input_slice.go
- input_tbln.go
- output_csv.go
- output_json.go
- output_ltsv.go
- output_raw.go
- output_slice.go
- output_tablewriter.go
- output_tbln.go
- output_vertical.go
- reader.go
- trdsql.go
- version.go
- writer.go
