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
- Variables
- func ConvertTypes(dbTypes []string) []string
- func EnableDebug()
- func ImportFile(db *DB, fileName string, readOpts *ReadOpts) (string, error)
- func SQLFields(query string) []string
- func TableNames(parsedQuery []string) (map[string]string, []int)
- func ValString(v interface{}) string
- type BufferImporter
- type CSVReader
- type CSVWriter
- type DB
- func (db *DB) CreateTable(tableName string, columnNames []string, columnTypes []string, isTemporary bool) error
- func (db *DB) Disconnect() error
- func (db *DB) Import(tableName string, columnNames []string, reader Reader) error
- func (db *DB) QuotedName(oldName string) 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.
Variables ¶
var ( // Error not starting transaction. // SQL must be executed within a transaction. ErrNoTransaction = errors.New("transaction has not been started") // The reader of the specified file is nil error. ErrNilReader = errors.New("nil reader") // Invalid column names (number of columns is 0). ErrInvalidNames = errors.New("invalid names") // Invalid column types (does not match the number of column names). ErrInvalidTypes = errors.New("invalid types") )
var Version = `v0.7.0`
Version is trdsql version
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 quoted table name and error. Do not import if file not found (no error). Wildcards can be passed as fileName.
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 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
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) Disconnect ¶ added in v0.6.0
Disconnect is disconnect the database.
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
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 // 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 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(";"),
)
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 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() ([]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 represents DB definition and Importer/Exporter interface.
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 represents the table data to be imported.
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 represents a structure that satisfies Exporter.
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 is the writing format.
OutFormat Format
// OutDelimiter is the output delimiter (Use only CSV and Raw).
OutDelimiter string
// OutHeader is true if it outputs a header(Use only CSV and Raw).
OutHeader bool
// OutStream is the output destination.
OutStream io.Writer
// ErrStream is the error output destination.
ErrStream io.Writer
}
WriteOpts represents options that determine the behavior of the writer.
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
