-
Notifications
You must be signed in to change notification settings - Fork 8
/
Copy pathdb.go
70 lines (63 loc) · 1.72 KB
/
db.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
package xutil
import (
"errors"
"fmt"
"io/ioutil"
"os"
"os/exec"
"path"
"regexp"
"runtime"
"strconv"
)
// Sqlldr 执行成功返回入库记录数,失败则保留log和data到baddir
func Sqlldr(timeflag, userid, data, control, baddir string) (
rows, badrows int, err error) {
if control == "" {
control = fmt.Sprintf("%s.ctl", data)
}
logfile := fmt.Sprintf("%s/%s.%s.log", baddir, path.Base(data), timeflag)
badfile := fmt.Sprintf("%s/%s.%s.bad", baddir, path.Base(data), timeflag)
var cmdout []byte
cmd := fmt.Sprintf("sqlldr userid=%s data=%s control=%s log=%s bad=%s", userid, data, control, logfile, badfile)
if runtime.GOOS == "windows" {
cmdout, err = exec.Command("cmd", "/C", cmd).CombinedOutput()
} else {
cmdout, err = exec.Command("bash", "-c", cmd).CombinedOutput()
}
rows, badrows, _ = sqlldrLog(logfile)
// 保留入库文件策略
if err == nil { // 执行成功
os.Remove(logfile)
os.Remove(data)
} else if rows > 0 { // 执行成功但有错误数据,保留log和bad文件
os.Remove(data)
} else { //执行失败
return rows, badrows, errors.New(string(cmdout))
}
return rows, badrows, nil
}
//sqlldrLog 从sqlldr的log文件中获取入库记录数
func sqlldrLog(logfile string) (rows, badrows int, err error) {
rowspat := regexp.MustCompile(`(\d+) Rows? successfully loaded`)
rowspatbad := regexp.MustCompile(`(\d+) Rows? not loaded due to data errors`)
src, err := ioutil.ReadFile(logfile)
if err != nil {
return
}
x := rowspat.FindSubmatch(src)
y := rowspatbad.FindSubmatch(src)
if len(x) > 1 {
rows, err = strconv.Atoi(string(x[1]))
if err != nil {
return
}
}
if len(y) > 1 {
badrows, err = strconv.Atoi(string(y[1]))
if err != nil {
return
}
}
return
}