-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathcsv.go
102 lines (88 loc) · 2.15 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
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
package sqltocsvgzip
import (
"bytes"
"encoding/csv"
"fmt"
"strconv"
"time"
)
func (c *Converter) getCSVWriter() (*csv.Writer, *bytes.Buffer) {
// Same size as sqlRowBatch
csvBuffer := bytes.NewBuffer(make([]byte, 0, c.CsvBufferSize))
// CSV writer to csvBuffer
csvWriter := csv.NewWriter(csvBuffer)
// Set delimiter
if c.Delimiter != '\x00' {
csvWriter.Comma = c.Delimiter
}
return csvWriter, csvBuffer
}
func (c *Converter) setCSVHeaders(csvWriter *csv.Writer) ([]string, int, error) {
var headers []string
columnNames, err := c.rows.Columns()
if err != nil {
return nil, 0, err
}
// Use Headers if set, otherwise default to
// query Columns
if len(c.Headers) > 0 {
headers = c.Headers
} else {
headers = columnNames
}
// Write to CSV Buffer
if c.WriteHeaders {
err = csvWriter.Write(headers)
if err != nil {
return nil, 0, err
}
csvWriter.Flush()
}
return headers, len(headers), nil
}
func (c *Converter) stringify(values []interface{}) []string {
row := make([]string, len(values), len(values))
for i, rawValue := range values {
if rawValue == nil {
row[i] = ""
continue
}
byteArray, ok := rawValue.([]byte)
if ok {
rawValue = string(byteArray)
}
switch castValue := rawValue.(type) {
case time.Time:
if c.TimeFormat != "" {
row[i] = castValue.Format(c.TimeFormat)
}
case bool:
row[i] = strconv.FormatBool(castValue)
case string:
row[i] = castValue
case int:
row[i] = strconv.FormatInt(int64(castValue), 10)
case int8:
row[i] = strconv.FormatInt(int64(castValue), 10)
case int16:
row[i] = strconv.FormatInt(int64(castValue), 10)
case int32:
row[i] = strconv.FormatInt(int64(castValue), 10)
case int64:
row[i] = strconv.FormatInt(int64(castValue), 10)
case uint:
row[i] = strconv.FormatUint(uint64(castValue), 10)
case uint8:
row[i] = strconv.FormatUint(uint64(castValue), 10)
case uint16:
row[i] = strconv.FormatUint(uint64(castValue), 10)
case uint32:
row[i] = strconv.FormatUint(uint64(castValue), 10)
case uint64:
row[i] = strconv.FormatUint(uint64(castValue), 10)
default:
row[i] = fmt.Sprintf("%v", castValue)
}
}
return row
}