/
pg_db_executor.go
79 lines (66 loc) · 1.4 KB
/
pg_db_executor.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
package postgres
import (
"database/sql"
"errors"
"github.com/aktau/gomig/db/common"
"github.com/lib/pq"
"log"
)
var (
PG_DB_EXECUTOR_VERBOSE = true
)
type PgDbExecutor struct {
common.DbExecutor
bulkStmt *sql.Stmt
}
func NewPgDbExecutor(db *sql.DB) (*PgDbExecutor, error) {
base, err := common.NewDbExecutor(db)
if err != nil {
return nil, err
}
return &PgDbExecutor{*base, nil}, nil
}
func (e *PgDbExecutor) BulkInit(table string, columns ...string) error {
db := e.GetDb()
if db == nil {
return errors.New("executor did not have a valid database")
}
var (
stmt *sql.Stmt
err error
)
tx := e.GetTx()
copySql := pq.CopyIn(table, columns...)
if tx == nil {
stmt, err = db.Prepare(copySql)
} else {
stmt, err = tx.Prepare(copySql)
}
if err != nil {
return err
}
e.bulkStmt = stmt
return nil
}
func (e *PgDbExecutor) BulkAddRecord(args ...interface{}) error {
/* TODO: does not check if bulkStmt exists yet */
_, err := e.bulkStmt.Exec(args...)
return err
}
func (e *PgDbExecutor) BulkFinish() error {
stmt := e.bulkStmt
defer func() { e.bulkStmt = nil }()
_, err := stmt.Exec()
if err != nil {
cerr := stmt.Close()
if cerr != nil {
log.Println("pg_executor: could not properly close bulk statement", cerr)
}
return err
}
err = stmt.Close()
return err
}
func (e *PgDbExecutor) HasCapability(capability int) bool {
return capability == common.CapBulkTransfer
}