-
Notifications
You must be signed in to change notification settings - Fork 128
/
import.go
85 lines (62 loc) · 1.51 KB
/
import.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
package main
import (
"database/sql"
"github.com/lib/pq"
)
type Import struct {
txn *sql.Tx
stmt *sql.Stmt
}
func NewCSVImport(db *sql.DB, schema string, tableName string, columns []string) (*Import, error) {
table, err := createTable(db, schema, tableName, columns)
if err != nil {
return nil, err
}
_, err = table.Exec()
if err != nil {
return nil, err
}
return newImport(db, schema, tableName, columns)
}
func NewJSONImport(db *sql.DB, schema string, tableName string, column string, dataType string) (*Import, error) {
table, err := createJSONTable(db, schema, tableName, column, dataType)
if err != nil {
return nil, err
}
_, err = table.Exec()
if err != nil {
return nil, err
}
return newImport(db, schema, tableName, []string{column})
}
func newImport(db *sql.DB, schema string, tableName string, columns []string) (*Import, error) {
txn, err := db.Begin()
if err != nil {
return nil, err
}
stmt, err := txn.Prepare(pq.CopyInSchema(schema, tableName, columns...))
if err != nil {
return nil, err
}
return &Import{txn, stmt}, nil
}
func (i *Import) AddRow(nullDelimiter string, columns ...interface{}) error {
for index := range columns {
column := columns[index]
if column == nullDelimiter {
columns[index] = nil
}
}
_, err := i.stmt.Exec(columns...)
return err
}
func (i *Import) Commit() error {
_, err := i.stmt.Exec()
if err != nil {
return err
}
// Statement might already be closed
// therefore ignore errors
_ = i.stmt.Close()
return i.txn.Commit()
}