forked from lukasmartinelli/pgfutter
-
Notifications
You must be signed in to change notification settings - Fork 3
/
import.go
82 lines (61 loc) · 1.36 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
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) (*Import, error) {
table, err := createJSONTable(db, schema, tableName, column)
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(columns ...interface{}) error {
_, err := i.stmt.Exec(columns...)
return err
}
func (i *Import) Commit() error {
_, err := i.stmt.Exec()
if err != nil {
return err
}
err = i.stmt.Close()
if err != nil {
return err
}
err = i.txn.Commit()
if err != nil {
return err
}
return nil
}