-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathdump.go
120 lines (102 loc) · 2.59 KB
/
dump.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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
package main
import (
"errors"
"fmt"
"io"
"os"
"os/exec"
"strconv"
"time"
)
type connectionOptions struct {
Host string
DbType string
Port int
Database string
Username string
Password string
}
var (
PGDumpCmd = "pg_dump"
pgDumpStdOpts = []string{"--no-owner", "--no-acl", "--clean", "--blobs", "-v"}
pgDumpDefaultFormat = "c"
ErrPgDumpNotFound = errors.New("pg_dump not found")
MysqlDumpCmd = "mysqldump"
mysqlDumpStdOpts = []string{"--compact", "--skip-add-drop-table", "--skip-add-locks", "--skip-disable-keys", "--skip-set-charset", "-v"}
ErrMySqlDumpNotFound = errors.New("mysqldump not found")
ErrUnsupportedType = errors.New("unsupported database type")
)
func RunDump(connectionOpts *connectionOptions, outFile string) error {
cmd, err := buildDumpCommand(connectionOpts, outFile)
if err != nil {
return err
}
return executeCommand(cmd)
}
func buildDumpCommand(opts *connectionOptions, outFile string) (*exec.Cmd, error) {
switch opts.DbType {
case "postgres":
if !commandExist(PGDumpCmd) {
return nil, ErrPgDumpNotFound
}
options := append(
pgDumpStdOpts,
fmt.Sprintf("-f%s", outFile),
fmt.Sprintf("--dbname=%s", opts.Database),
fmt.Sprintf("--host=%s", opts.Host),
fmt.Sprintf("--port=%d", opts.Port),
fmt.Sprintf("--username=%s", opts.Username),
fmt.Sprintf("--format=%s", pgDumpDefaultFormat),
)
return exec.Command(PGDumpCmd, options...), nil
case "mysql":
mysqldumpCmd := "mysqldump"
if !commandExist(mysqldumpCmd) {
return nil, ErrMySqlDumpNotFound
}
options := append(
mysqlDumpStdOpts,
"-h", opts.Host,
"-P", strconv.Itoa(opts.Port),
"-u", opts.Username,
fmt.Sprintf("--password=%s", opts.Password),
"--databases", opts.Database,
"-r", outFile,
)
return exec.Command(mysqldumpCmd, options...), nil
default:
return nil, ErrUnsupportedType
}
}
func executeCommand(cmd *exec.Cmd) error {
stderr, err := cmd.StderrPipe()
if err != nil {
return err
}
stdout, err := cmd.StdoutPipe()
if err != nil {
return err
}
go io.Copy(os.Stderr, stderr)
go io.Copy(os.Stdout, stdout)
if err := cmd.Start(); err != nil {
return err
}
if err := cmd.Wait(); err != nil {
return err
}
return nil
}
func commandExist(command string) bool {
_, err := exec.LookPath(command)
return err == nil
}
func newFileName(db string, dbType string) string {
switch dbType {
case "postgres":
return fmt.Sprintf(`%v_%v.pgdump`, db, time.Now().Unix())
case "mysql":
return fmt.Sprintf(`%v_%v.sql`, db, time.Now().Unix())
}
return fmt.Sprintf(`%v_%v`, db, time.Now().Unix())
}