forked from dinedal/textql
/
csv.go
82 lines (65 loc) · 1.77 KB
/
csv.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
package outputs
import (
"database/sql"
"encoding/csv"
"io"
"log"
)
// CSVOutput represents a TextQL output that transforms sql.Rows into CSV formatted
// string data using encoding/csv
type CSVOutput struct {
options *CSVOutputOptions
writer *csv.Writer
firstRow []string
header []string
minOutputLength int
}
// CSVOutputOptions define options that are passed to encoding/csv for formatting
// the output in specific ways.
type CSVOutputOptions struct {
// WriteHeader determines if a header row based on the column names should be written.
WriteHeader bool
// Separator is the rune used to delimit fields.
Separator rune
// WriteTo is where the formatted data will be written to.
WriteTo io.Writer
}
// NewCSVOutput returns a new CSVOutput configured per the options provided.
func NewCSVOutput(opts *CSVOutputOptions) *CSVOutput {
csvOutput := &CSVOutput{
options: opts,
writer: csv.NewWriter(opts.WriteTo),
}
csvOutput.writer.Comma = csvOutput.options.Separator
return csvOutput
}
// Show writes the sql.Rows given to the destination in CSV format.
func (csvOutput *CSVOutput) Show(rows *sql.Rows) {
cols, colsErr := rows.Columns()
if colsErr != nil {
log.Fatalln(colsErr)
}
if csvOutput.options.WriteHeader && len(cols) > 0 {
if err := csvOutput.writer.Write(cols); err != nil {
log.Fatalln(err)
}
}
rawResult := make([][]byte, len(cols))
result := make([]string, len(cols))
dest := make([]interface{}, len(cols))
for i := range cols {
dest[i] = &rawResult[i]
}
for rows.Next() {
rows.Scan(dest...)
for i, raw := range rawResult {
result[i] = string(raw)
}
writeErr := csvOutput.writer.Write(result)
if writeErr != nil {
log.Fatalln(writeErr)
}
}
csvOutput.writer.Flush()
rows.Close()
}