-
Notifications
You must be signed in to change notification settings - Fork 1
/
pq.go
86 lines (67 loc) · 1.32 KB
/
pq.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
86
package gel
import (
"bytes"
"io"
"log"
"os"
"os/exec"
)
// pSQLWorker
func pSQLWorker(sql string) func(io.WriteCloser) {
return func(stdin io.WriteCloser) {
io.Copy(stdin, bytes.NewBufferString(sql))
io.Copy(stdin, bytes.NewBufferString("\\q\r"))
stdin.Close()
}
}
// PostgrSQL Commander
func pSQLCommander(processPSQLWorker func(io.WriteCloser)) {
// build command
args := []string{"-v", "ON_ERROR_STOP=1", "-d", "ensure"}
cmd := exec.Command("psql", args...)
// pipe out
stdout, err := cmd.StdoutPipe()
if err != nil {
log.Printf("Error pipe stdout")
log.Panic(err)
}
// pipe in
stdin, err := cmd.StdinPipe()
if err != nil {
log.Printf("Error pipe stdin")
log.Panic(err)
}
stderr, err := cmd.StderrPipe()
if err != nil {
log.Printf("Error pipe stderr")
log.Panic(err)
}
// defers
defer stdout.Close()
defer stderr.Close()
defer stdin.Close()
// pipe to STDIN
go processPSQLWorker(stdin)
// pipe to STDOUT
go io.Copy(os.Stdout, stdout)
// pipe to STDERR
go io.Copy(os.Stderr, stderr)
// run
err = cmd.Start()
// panic
if err != nil {
log.Printf("Error start")
log.Panic(err)
}
// wait
err = cmd.Wait()
// trace error
if err != nil {
log.Printf("Error wait")
log.Fatal(err)
}
}
// PostgrSQL Dump (RUN here)
func PQDump(sql string) {
pSQLCommander(pSQLWorker(sql))
}