-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathcsv.go
189 lines (154 loc) · 3.96 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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
package main
import (
"compress/gzip"
"encoding/json"
"errors"
"fmt"
"io"
"log"
"os"
"strings"
"unicode/utf8"
csv "github.com/JensRantil/go-csv"
"github.com/cheggaaa/pb"
)
func containsDelimiter(col string) bool {
return strings.Contains(col, ";") || strings.Contains(col, ",") ||
strings.Contains(col, "|") || strings.Contains(col, "\t") ||
strings.Contains(col, "^") || strings.Contains(col, "~")
}
// Parse columns from first header row or from flags
func parseColumns(reader *csv.Reader, skipHeader bool, fields string) ([]string, error) {
var err error
var columns []string
if fields != "" {
columns = strings.Split(fields, ",")
if skipHeader {
reader.Read() //Force consume one row
}
} else {
columns, err = reader.Read()
fmt.Printf("%v columns\n%v\n", len(columns), columns)
if err != nil {
fmt.Printf("FOUND ERR\n")
return nil, err
}
}
for _, col := range columns {
if containsDelimiter(col) {
return columns, errors.New("Please specify the correct delimiter with -d.\n" +
"Header column contains a delimiter character: " + col)
}
}
//for i, col := range columns {
// columns[i] = postgresify(col)
//}
return columns, nil
}
func copyCSVRows(itemChan ItemsChannel, reader *csv.Reader, ignoreErrors bool,
delimiter string, nullDelimiter string) (error, int, int) {
success := 0
failed := 0
items := Items{}
for {
item := Item{}
columns := item.Columns()
cols := make([]interface{}, len(columns))
record, err := reader.Read()
if err == io.EOF {
break
}
if err != nil {
line := strings.Join(record, delimiter)
failed++
if ignoreErrors {
os.Stderr.WriteString(string(line))
continue
} else {
err = fmt.Errorf("%s: %s", err, line)
return err, success, failed
}
}
var itemMap = make(map[string]interface{})
//Loop ensures we don't insert too many values and that
//values are properly converted into empty interfaces
for i, col := range record {
cols[i] = strings.Replace(col, "\x00", "", -1)
// bytes.Trim(b, "\x00")
// cols[i] = col
itemMap[columns[i]] = record[i]
}
// marschall it to bytes
b, _ := json.Marshal(itemMap)
// fill the new Item instance with values
if err := json.Unmarshal([]byte(b), &item); err != nil {
line := strings.Join(record, delimiter)
failed++
if ignoreErrors {
os.Stderr.WriteString(string(line))
continue
} else {
err = fmt.Errorf("%s: %s", err, line)
return err, success, failed
}
}
if len(items) > 100000 {
itemChan <- items
items = Items{}
}
items = append(items, &item)
success++
}
// add leftover items
itemChan <- items
return nil, success, failed
}
func importCSV(filename string, itemChan ItemsChannel,
ignoreErrors bool, skipHeader bool,
delimiter string, nullDelimiter string) error {
dialect := csv.Dialect{}
dialect.Delimiter, _ = utf8.DecodeRuneInString(delimiter)
var reader *csv.Reader
var bar *pb.ProgressBar
if filename != "" {
file, err := os.Open(filename)
if err != nil {
return err
}
defer file.Close()
bar = NewProgressBar(file)
fz, err := gzip.NewReader(io.TeeReader(file, bar))
if err != nil {
return err
}
defer fz.Close()
reader = csv.NewDialectReader(fz, dialect)
} else {
reader = csv.NewDialectReader(os.Stdin, dialect)
}
var err error
_, err = parseColumns(reader, skipHeader, "")
if err != nil {
log.Fatal(err)
}
var success, failed int
if filename != "" {
bar.Start()
err, success, failed = copyCSVRows(itemChan, reader, ignoreErrors, delimiter, nullDelimiter)
bar.Finish()
} else {
err, success, failed = copyCSVRows(itemChan, reader, ignoreErrors, delimiter, nullDelimiter)
}
if err != nil {
lineNumber := success + failed
if !skipHeader {
lineNumber++
}
return fmt.Errorf("line %d: %s", lineNumber, err)
}
fmt.Printf("%d rows imported", success)
if ignoreErrors && failed > 0 {
fmt.Printf("%d rows could not be imported and have been written to stderr.", failed)
}
return err
}