-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathbulk.go
68 lines (56 loc) · 1.17 KB
/
bulk.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
package npidb
import (
"database/sql"
"encoding/csv"
"fmt"
"io"
"time"
mssql "github.com/denisenkom/go-mssqldb"
"github.com/paulbellamy/ratecounter"
)
func WriteCsvToDb(reader io.Reader, txn *sql.Tx, tableName string) (headers []string, err error) {
csvReader := csv.NewReader(reader)
headers, err = csvReader.Read()
if err != nil {
return
}
bulk := mssql.CopyIn(tableName, mssql.MssqlBulkOptions{}, headers...)
stmt, err := txn.Prepare(bulk)
if err != nil {
return
}
counter := ratecounter.NewRateCounter(60 * time.Second)
fmt.Printf("Loading into %s\n", tableName)
for {
var row []string
row, err = csvReader.Read()
if err != nil {
if err == io.EOF {
break
}
return
}
fields := make([]interface{}, len(row))
for i, v := range row {
fields[i] = v
}
_, err = stmt.Exec(fields...)
if err != nil {
return
}
counter.Incr(1)
fmt.Printf("\r%d rows/s", counter.Rate()/60)
}
fmt.Printf("\nFinishing write to %s\n", tableName)
result, err := stmt.Exec()
if err != nil {
return
}
err = stmt.Close()
if err != nil {
return
}
rowCount, _ := result.RowsAffected()
fmt.Printf("%d rows inserted\n", rowCount)
return
}