trdsql

package module
v0.7.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 22, 2019 License: MIT Imports: 25 Imported by: 15

README

trdsql

GoDoc Build Status

A tool that can execute SQL queries on CSV, LTSV, JSON and TBLN.

It is a tool like q , textql and others.

The difference from these tools is that the syntax of PostgreSQL or MySQL can be used.

Please refer to godoc and _example for usage as a library.

trdsql.gif

INSTALL

go get -d github.com/noborus/trdsql
cd $GOPATH/src/github.com/noborus/trdsql
make
make install
Requirements

go 1.11 or higher.

Download

Download binary from the releases page(Linux/Windows/macOS).

Docker

image build.

docker build -t trdsql .

docker run.

docker run --rm -it -v $(pwd)/tmp trdsql [options and commands]

Usage

$ trdsql [options] SQL
global option
  • -config filename Configuration file location.
  • -db db name Specify db name of the setting.
  • -dblist Display db list of configure.
  • -driver driver name database driver. [ mysql | postgres | sqlite3 ]
  • -dsn dsn string database connection option.
  • -debug debug print.
  • -help display usage information.
  • -version display version information.
  • -q filename Read query from the provided filename.
Input format
  • -ig Guess format from extension(default).
  • -icsv CSV format for input.
  • -ijson JSON format for input.
  • -iltsv LTSV format for input.
  • -itbln TBLN format for input.
Input option
  • -ih The first line is interpreted as column names(CSV only).
  • -id delimiter character(CSV only) Field delimiter for input. (default ",")
  • -is int Skip header row.
  • -ir int Number of row pre-read for column determination. (default 1)
Output format
  • -ocsv CSV format for output. (default)
  • -ojson JSON format for output.
  • -oltsv LTSV format for output.
  • -oat ASCII Table format for output.
  • -omd Mark Down format for output.
  • -oraw Raw format for output.
  • -ovf Vertical format for output.
  • -otbln TBLN format for output.
Output option
  • -oh Output column name as header.
  • -od delimiter character Field delimiter for output. (default ",")

Example

test.csv file.

1,Orange
2,Melon
3,Apple

Please write a file name like a table name.

$ trdsql "SELECT * FROM test.csv"

-q filename can execute SQL from file

$ trdsql -q test.sql
STDIN input

"-" or "stdin" is received from standard input instead of file name.

$ ps | trdsql -id " " "SELECT * FROM -"

or

$ ps | trdsql -id " " "SELECT * FROM stdin"
Multiple files

Multiple matched files can be executed as one table.

$ trdsql -ih "SELECT * FROM tt*.csv"
1,test1
2,test2
3,test3

Note: It is not possible to mix different formats (ex: CSV and LTSV).

Expand gzip

Files with the file name suffix of ".gz" are automatically expanded.

$ trdsql "SELECT * FROM testdata/test.csv.gz"

It is possible to mix uncompressed and compressed files using wildcards.

$ trdsql "SELECT * FROM testdata/test.csv*"
Columns is not constant

If the number of columns is not a constant, read and decide multiple rows.

$ trdsql -ir 3 -iltsv "SELECT * FROM test_indefinite.ltsv"
1,Orange,50,,
2,Melon,500,ibaraki,
3,Apple,100,aomori,red
TSV (Tab Separated Value)

-id "\t" is input from TSV (Tab Separated Value)

1	Orange
2	Melon
3	Apple
$ trdsql -id "\t" "SELECT * FROM test-tab.csv"

-od "\t" is TSV (Tab Separated Value) output.

$ trdsql -od "\t" "SELECT * FROM test.csv"
1	Orange
2	Melon
3	Apple
LTSV (Labeled Tab-separated Values)

-iltsv is input from LTSV(Labeled Tab-separated Values).

sample.ltsv

id:1	name:Orange	price:50
id:2	name:Melon	price:500
id:3	name:Apple	price:100
$ trdsql -iltsv "SELECT * FROM sample.ltsv"
1,Orange,50
2,Melon,500
3,Apple,100

Note: Only the columns in the first row are targeted.

-oltsv is LTSV(Labeled Tab-separated Values) output.

$ trdsql -iltsv -oltsv "SELECT * FROM sample.ltsv"
id:1	name:Orange	price:50
id:2	name:Melon	price:500
id:3	name:Apple	price:100
JSON

-ijson is input from JSON.

sample.json

[
  {
    "id": "1",
    "name": "Orange",
    "price": "50"
  },
  {
    "id": "2",
    "name": "Melon",
    "price": "500"
  },
  {
    "id": "3",
    "name": "Apple",
    "price": "100"
  }
]
$ trdsql -ijson "SELECT * FROM sample.json"
1,Orange,50
2,Melon,500
3,Apple,100

JSON can contain structured types, but trdsql is stored as it is as JSON string.

sample2.json

[
    {
      "id": 1,
      "name": "Drolet",
      "attribute": { "country": "Maldives", "color": "burlywood" }
    },
    {
      "id": 2,
      "name": "Shelly",
      "attribute": { "country": "Yemen", "color": "plum" }
    },
    {
      "id": 3,
      "name": "Tuck",
      "attribute": { "country": "Mayotte", "color": "antiquewhite" }
    }
]
$ trdsql -ijson "SELECT * FROM sample2.json"
1,Drolet,"{""color"":""burlywood"",""country"":""Maldives""}"
2,Shelly,"{""color"":""plum"",""country"":""Yemen""}"
3,Tuck,"{""color"":""antiquewhite"",""country"":""Mayotte""}"

Please use SQL function.

$ trdsql -ijson "SELECT id, name, JSON_EXTRACT(attribute,'$country'), JSON_EXTRACT(attribute,'$color') FROM sample2.json"
1,Drolet,Maldives,burlywood
2,Shelly,Yemen,plum
3,Tuck,Mayotte,antiquewhite

Another json format. One record is JSON.

sample2.json

{
  "id": "1",
  "name": "Orange",
  "price": "50"
}
{
  "id": "2",
  "name": "Melon",
  "price": "500"
}
{
  "id": "3",
  "name": "Apple",
  "price": "100"
}

-ojson is JSON Output.

$ trdsql -ojson "SELECT * FROM test.csv"
[
  {
    "c1": "1",
    "c2": "Orange"
  },
  {
    "c1": "2",
    "c2": "Melon"
  },
  {
    "c1": "3",
    "c2": "Apple"
  }
]
TBLN

-itbln is input from TBLN.

sample.tbln

; name: | id | name |
; type: | int | text |
| 1 | Bob |
| 2 | Alice |
$ trdsql -itbln "SELECT * FROM sample.tbln"
1,Bob
2,Alice

TBLN file reflects extras name and type.

-otbln is TBLN Output.

$ trdsql -otbln "SELECT c1::int as id, c2::text as name FROM test.csv"
; created_at: 2019-03-22T13:20:31+09:00
; name: | id | name |
; type: | int | text |
| 1 | Orange |
| 2 | Melon |
| 3 | Apple |

TBLN can contain column names and type definitions. Please refer to https://tbln.dev/ for details of TBLN.

Raw output

-oraw is Raw Output. It is used when "escape processing is unnecessary" in CSV output. (For example, when outputting JSON in the database).

$ trdsql -oraw "SELECT row_to_json(t,TRUE) FROM test.csv AS t"
{"c1":"1",
 "c2":"Orange"}
{"c1":"2",
 "c2":"Melon"}
{"c1":"3",
 "c2":"Apple"}

Multiple delimiter characters can be used for raw.

$ trdsql -oraw -od "\t|\t" -db pdb "SELECT * FROM test.csv"
1	|	Orange
2	|	Melon
3	|	Apple
ASCII Table & MarkDown output

-oat is ASCII table output.

$ trdsql -oat "SELECT * FROM test.csv"
+----+--------+
| C1 |   C2   |
+----+--------+
|  1 | Orange |
|  2 | Melon  |
|  3 | Apple  |
+----+--------+

-omd is Markdown output.

$ trdsql -omd "SELECT * FROM test.csv"
| C1 |   C2   |
|----|--------|
|  1 | Orange |
|  2 | Melon  |
|  3 | Apple  |
Vertical format output

-ovf is Vertical format output("column name | value" vertically).

$ trdsql -ovf "SELECT * FROM test.csv"
---[ 1]--------------------------------------------------------
  c1 | 1
  c2 | Orange
---[ 2]--------------------------------------------------------
  c1 | 2
  c2 | Melon
---[ 3]--------------------------------------------------------
  c1 | 3
  c2 | Apple
SQL function
$ trdsql "SELECT count(*) FROM test.csv"
3

The default column names are c1, c2,...

$ trdsql "SELECT c2,c1 FROM test.csv"
Orange,1
Melon,2
Apple,3

"- ih" sets the first line to column name

$ ps |trdsql -ih -oh -id " " "SELECT \"TIME\",\"TTY\",\"PID\",\"CMD\" FROM -"
TIME,TTY,PID,CMD
00:00:00,pts/20,3452,ps
00:00:00,pts/20,3453,trdsql
00:00:05,pts/20,15576,zsh
JOIN

The SQL JOIN can be used.

user.csv

1,userA
2,userB

hist.csv

1,2017-7-10
2,2017-7-10
2,2017-7-11
$ trdsql "SELECT u.c1,u.c2,h.c2 FROM user.csv as u LEFT JOIN hist.csv as h ON(u.c1=h.c1)"
1,userA,2017-7-10
2,userB,2017-7-10
2,userB,2017-7-11
PostgreSQL

When using PostgreSQL, specify postgres for driver and connection information for dsn.

$ trdsql -driver postgres -dsn "dbname=test" "SELECT count(*) FROM test.csv "
Function

The PostgreSQL driver can use the window function.

$ trdsql -driver postgres -dsn "dbname=test" "SELECT row_number() OVER (ORDER BY c2),c1,c2 FROM test.csv"
1,3,Apple
2,2,Melon
3,1,Orange

For example, the generate_series function can be used.

$ trdsql -driver postgres -dsn "dbname=test" "SELECT generate_series(1,3);"
1
2
3
Join table and CSV file is possible.

Test database has a colors table.

$ psql test -c "SELECT * FROM colors"
 id |  name  
----+--------
  1 | orange
  2 | green
  3 | red
(3 rows)

Join table and CSV file.

$ trdsql -driver postgres -dsn "dbname=test" "SELECT t.c1,t.c2,c.name FROM test.csv AS t LEFT JOIN colors AS c ON (t.c1::int = c.id)"
1,Orange,orange
2,Melon,green
3,Apple,red

To create a table from a file, use "CREATE TABLE ... AS SELECT...".

$ trdsql -driver postgres -dns "dbname=test" "CREATE TABLE fruits (id, name) AS SELECT c1::int, c2 FROM fruits.csv "
$ psql -c "SELECT * FROM fruits;"
 id |  name  
----+--------
  1 | Orange
  2 | Melon
  3 | Apple
(3 rows)
MySQL

When using MySQL, specify mysql for driver and connection information for dsn.

$ trdsql -driver mysql -dsn "user:password@/test" "SELECT GROUP_CONCAT(c2 ORDER BY c2 DESC) FROM testdata/test.csv"
"g,d,a"
$ trdsql -driver mysql -dsn "user:password@/test" "SELECT c1, SHA2(c2,224) FROM test.csv"
1,a063876767f00792bac16d0dac57457fc88863709361a1bb33f13dfb
2,2e7906d37e9523efeefb6fd2bc3be6b3f2991678427bedc296f9ddb6
3,d0b8d1d417a45c7c58202f55cbb617865f1ef72c606f9bce54322802

MySQL can join tables and CSV files as well as PostgreSQL.

configuration

You can specify driver and dsn in the configuration file.

Unix like.

${HOME}/.config/trdsql/config.json

Windows (ex).

C:\Users\{"User"}\AppData\Roaming\trdsql\config.json

Or use the -config file option.

$ trdsql -config config.json "SELECT * FROM test.csv"

sample: config.json

{
  "db": "pdb",
  "database": {
    "sdb": {
      "driver": "sqlite3",
      "dsn": ""
    },
    "pdb": {
      "driver": "postgres",
      "dsn": "user=test dbname=test"
    },
    "mdb": {
      "driver": "mysql",
      "dsn": "user:password@/dbname"
    }
  }
}

The default database is an entry of "db".

If you put the setting in you can specify the name with -db.

$ trdsql -debug -db pdb "SELECT * FROM test.csv"
2017/07/18 02:27:47 driver: postgres, dsn: user=test dbname=test
2017/07/18 02:27:47 CREATE TEMPORARY TABLE "test.csv" ( c1 text,c2 text );
2017/07/18 02:27:47 INSERT INTO "test.csv" (c1,c2) VALUES ($1,$2);
2017/07/18 02:27:47 SELECT * FROM "test.csv"
1,Orange
2,Melon
3,Apple

Library

Example of use as a library.

package main

import (
        "log"

        "github.com/noborus/trdsql"
)

func main() {
        trd := trdsql.NewTRDSQL(
                trdsql.NewImporter(trdsql.InDelimiter(":")),
                trdsql.NewExporter(trdsql.NewWriter()),
        )
        err := trd.Exec("SELECT c1 FROM /etc/passwd")
        if err != nil {
                log.Fatal(err)
        }
}

Please refer to godoc and _example for usage as a library.

See also psutilsql, which uses trdsql as a library.

License

MIT

Please check each license of SQL driver.

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

Examples

Constants

View Source
const DefaultDBType = "text"

DefaultDBType is default type.

Variables

View Source
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")
)
View Source
var Version = `v0.7.0`

Version is trdsql version

Functions

func ConvertTypes added in v0.6.0

func ConvertTypes(dbTypes []string) []string

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

func ImportFile(db *DB, fileName string, readOpts *ReadOpts) (string, error)

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

func SQLFields(query string) []string

SQLFields returns an array of string fields (interpreting quotes) from the argument query.

func TableNames added in v0.6.3

func TableNames(parsedQuery []string) (map[string]string, []int)

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.

func ValString added in v0.6.0

func ValString(v interface{}) string

ValString converts database value to string.

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

func NewBufferImporter(tableName string, r io.Reader, options ...ReadOpt) (*BufferImporter, error)

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.

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

func NewCSVReader(reader io.Reader, opts *ReadOpts) (*CSVReader, error)

NewCSVReader returns CSVReader and error.

func (*CSVReader) Names added in v0.6.0

func (r *CSVReader) Names() ([]string, error)

Names returns column names.

func (*CSVReader) PreReadRow added in v0.6.0

func (r *CSVReader) PreReadRow() [][]interface{}

PreReadRow is returns only columns that store preread rows.

func (*CSVReader) ReadRow added in v0.6.0

func (r *CSVReader) ReadRow(row []interface{}) ([]interface{}, error)

ReadRow is read the rest of the row.

func (*CSVReader) Types added in v0.6.0

func (r *CSVReader) Types() ([]string, error)

Types returns column types. All CSV types return the DefaultDBType.

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

func NewCSVWriter(writeOpts *WriteOpts) *CSVWriter

NewCSVWriter returns CSVWriter.

func (*CSVWriter) PostWrite added in v0.6.0

func (w *CSVWriter) PostWrite() error

PostWrite is flush.

func (*CSVWriter) PreWrite added in v0.6.0

func (w *CSVWriter) PreWrite(columns []string, types []string) error

PreWrite is output of header and preparation.

func (*CSVWriter) WriteRow added in v0.6.0

func (w *CSVWriter) WriteRow(values []interface{}, columns []string) error

WriteRow is row write.

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

func Connect(driver, dsn string) (*DB, error)

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

func (db *DB) Disconnect() error

Disconnect is disconnect the database.

func (*DB) Import added in v0.6.0

func (db *DB) Import(tableName string, columnNames []string, reader Reader) error

Import is imports data into a table.

func (*DB) QuotedName added in v0.7.0

func (db *DB) QuotedName(oldName string) string

QuotedName returns the table name quoted. Returns as is, if already quoted.

func (*DB) Select added in v0.6.0

func (db *DB) Select(query string) (*sql.Rows, error)

Select is executes SQL select statements.

type Exporter added in v0.6.0

type Exporter interface {
	Export(db *DB, query 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

	// 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

func (Format) String added in v0.6.0

func (f Format) String() string

type Importer added in v0.6.0

type Importer interface {
	Import(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 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

func NewRAWWriter(writeOpts *WriteOpts) *RAWWriter

NewRAWWriter returns RAWWriter.

func (*RAWWriter) PostWrite added in v0.6.0

func (w *RAWWriter) PostWrite() error

PostWrite is flush.

func (*RAWWriter) PreWrite added in v0.6.0

func (w *RAWWriter) PreWrite(columns []string, types []string) error

PreWrite is output of header and preparation.

func (*RAWWriter) WriteRow added in v0.6.0

func (w *RAWWriter) WriteRow(values []interface{}, columns []string) error

WriteRow is row write.

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.

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

func InDelimiter(d string) ReadOpt

InDelimiter is the field delimiter.

func InFormat added in v0.6.0

func InFormat(f Format) ReadOpt

InFormat is read format.

func InHeader added in v0.6.0

func InHeader(h bool) ReadOpt

InHeader is true if there is a header.

func InPreRead added in v0.6.0

func InPreRead(p int) ReadOpt

InPreRead is number of lines to read ahead.

func InSkip added in v0.6.0

func InSkip(s int) ReadOpt

InSkip is number of lines to skip.

func IsTemporary added in v0.6.0

func IsTemporary(t bool) ReadOpt

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

func NewReadOpts(options ...ReadOpt) *ReadOpts

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.

func NewReader added in v0.6.0

func NewReader(reader io.Reader, readOpts *ReadOpts) (Reader, error)

NewReader returns an Reader interface depending on the file to be imported.

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.

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.

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

func NewTBLNReader(reader io.Reader) (*TBLNRead, error)

NewTBLNReader returns TBLNRead and error.

func (*TBLNRead) Names added in v0.6.0

func (r *TBLNRead) Names() ([]string, error)

Names returns column names.

func (*TBLNRead) PreReadRow added in v0.6.0

func (r *TBLNRead) PreReadRow() [][]interface{}

PreReadRow is returns only columns that store preread rows.

func (*TBLNRead) ReadRow added in v0.6.0

func (r *TBLNRead) ReadRow(row []interface{}) ([]interface{}, error)

ReadRow is read the rest of the row.

func (*TBLNRead) Types added in v0.6.0

func (r *TBLNRead) Types() ([]string, error)

Types returns column types.

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.

func NewTRDSQL added in v0.6.0

func NewTRDSQL(im Importer, ex Exporter) *TRDSQL

NewTRDSQL returns a new TRDSQL structure.

func (*TRDSQL) Exec added in v0.6.0

func (trd *TRDSQL) Exec(sql string) error

Exec is actually executed.

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

func NewTWWriter(writeOpts *WriteOpts, markdown bool) *TWWriter

NewTWWriter returns TWWriter.

func (*TWWriter) PostWrite added in v0.6.0

func (w *TWWriter) PostWrite() error

PostWrite is Actual output.

func (*TWWriter) PreWrite added in v0.6.0

func (w *TWWriter) PreWrite(columns []string, types []string) error

PreWrite is preparation.

func (*TWWriter) WriteRow added in v0.6.0

func (w *TWWriter) WriteRow(values []interface{}, columns []string) error

WriteRow is Addition to array.

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

func NewVFWriter(writeOpts *WriteOpts) *VFWriter

NewVFWriter returns VFWriter.

func (*VFWriter) PostWrite added in v0.6.0

func (w *VFWriter) PostWrite() error

PostWrite is flush.

func (*VFWriter) PreWrite added in v0.6.0

func (w *VFWriter) PreWrite(columns []string, types []string) error

PreWrite is preparation.

func (*VFWriter) WriteRow added in v0.6.0

func (w *VFWriter) WriteRow(values []interface{}, columns []string) error

WriteRow is Actual output.

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.

func (*WriteFormat) Export added in v0.6.0

func (e *WriteFormat) Export(db *DB, query string) error

Export is execute SQL(Select) and the result is written out by the writer. Export is called from Exec.

type WriteOpt added in v0.6.0

type WriteOpt func(*WriteOpts)

WriteOpt is a function to set WriteOpts.

func ErrStream added in v0.6.0

func ErrStream(w io.Writer) WriteOpt

ErrStream sets the error output destination.

func OutDelimiter added in v0.6.0

func OutDelimiter(d string) WriteOpt

OutDelimiter sets delimiter.

func OutFormat added in v0.6.0

func OutFormat(f Format) WriteOpt

OutFormat sets Format.

func OutHeader added in v0.6.0

func OutHeader(h bool) WriteOpt

OutHeader sets flag to output header.

func OutStream added in v0.6.0

func OutStream(w io.Writer) WriteOpt

OutStream sets the output destination.

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.

type Writer added in v0.6.0

type Writer interface {
	PreWrite([]string, []string) error
	WriteRow([]interface{}, []string) error
	PostWrite() error
}

Writer is file format writer. Writer is a group of methods called from Export.

func NewWriter added in v0.6.0

func NewWriter(options ...WriteOpt) Writer

NewWriter returns a Writer interface. The argument is an option of Functional Option Pattern.

usage:

NewWriter(
	trdsql.OutFormat(trdsql.CSV),
	trdsql.OutHeader(true),
	trdsql.OutDelimiter(";"),
)

Directories

Path Synopsis
_example
buffer command
import command
quotecsv command
simple command
slice command
cmd
trdsql command

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL