-
Notifications
You must be signed in to change notification settings - Fork 0
/
csv_insert_engine.go
78 lines (72 loc) · 1.63 KB
/
csv_insert_engine.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
package csvdriver
import (
"database/sql/driver"
"encoding/csv"
"errors"
"io"
"os"
"github.com/blastrain/vitess-sqlparser/sqlparser"
)
func insertRows(fi *os.File, parser *sqlparser.Insert, args []driver.Value) error {
row := parser.Rows.(sqlparser.Values)
rowVal, err := getInsertRows(row, args)
if err != nil {
return err
}
cols, err := getInsertCol(fi, parser)
if err != nil {
return err
}
actualInsertRow := []string{}
for i := range cols {
if len(rowVal)-1 < i {
actualInsertRow = append(actualInsertRow, "<null>")
} else {
actualInsertRow = append(actualInsertRow, rowVal[i])
}
}
return writeCSV(fi, actualInsertRow)
}
// 获取要插入的数据
func getInsertRows(rows sqlparser.Values, args []driver.Value) ([]string, error) {
rowVals := []string{}
for _, tupleRows := range rows {
for _, item := range tupleRows {
val := item.(*sqlparser.SQLVal)
strVal, err := parseArg(val, args)
if err != nil {
return nil, err
}
rowVals = append(rowVals, strVal)
}
}
return rowVals, nil
}
// 获取要插入的列
func getInsertCol(fi *os.File, parser *sqlparser.Insert) ([]string, error) {
cols := []string{}
for _, col := range parser.Columns {
cols = append(cols, col.String())
}
if len(cols) != 0 {
return cols, nil
}
_, err := fi.Seek(0, io.SeekStart)
if err != nil {
return nil, err
}
reader := csv.NewReader(fi)
header, err := reader.Read()
if err != nil {
if err == io.EOF {
return nil, errors.New(`table not exists`)
} else {
return nil, err
}
}
cols = append(cols, header...)
if len(cols) == 0 {
return nil, errors.New("header len is 0")
}
return cols, nil
}