-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpg_restore.go
95 lines (80 loc) · 2.23 KB
/
pg_restore.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
package pgcommands
import (
"fmt"
"os"
"os/exec"
"strings"
)
var (
// PGRestoreCmd is the path to the `pg_restore` executable
PGRestoreCmd = "pg_restore"
pgDRestoreStdOpts = []string{"--no-owner", "--no-acl", "--clean", "--exit-on-error"}
)
type Restore struct {
*Postgres
// Verbose mode
Verbose bool
// Role: do SET ROLE before restore
Role string
// Path: setup path for source restore
Path string
// Extra pg_dump options
// e.g []string{"--inserts"}
Options []string
// Schemas: list of database schema
Schemas []string
}
func NewRestore(pg *Postgres) (*Restore, error) {
if !CommandExist(PGRestoreCmd) {
return nil, &ErrCommandNotFound{Command: PGRestoreCmd}
}
return &Restore{Options: pgDRestoreStdOpts, Postgres: pg, Schemas: []string{"public"}}, nil
}
// Exec `pg_restore` of the specified database, and restore from a gzip compressed tarball archive.
func (x *Restore) Exec(filename string, opts ExecOptions) Result {
result := Result{}
options := append(x.restoreOptions(), fmt.Sprintf("%s%s", x.Path, filename))
result.FullCommand = strings.Join(options, " ")
cmd := exec.Command(PGRestoreCmd, options...)
cmd.Env = append(os.Environ(), x.EnvPassword)
stderrIn, _ := cmd.StderrPipe()
go streamOutput(stderrIn, opts, &result)
err := cmd.Start()
if err != nil {
result.Error = &ResultError{Err: err, CmdOutput: result.Output}
}
err = cmd.Wait()
if exitError, ok := err.(*exec.ExitError); ok {
result.Error = &ResultError{Err: err, ExitCode: exitError.ExitCode(), CmdOutput: result.Output}
}
return result
}
func (x *Restore) ResetOptions() {
x.Options = []string{}
}
func (x *Restore) EnableVerbose() {
x.Verbose = true
}
func (x *Restore) SetPath(path string) {
x.Path = path
}
func (x *Restore) SetSchemas(schemas []string) {
x.Schemas = schemas
}
func (x *Restore) restoreOptions() []string {
options := x.Options
options = append(options, x.Postgres.Parse()...)
if x.Role != "" {
options = append(options, fmt.Sprintf(`--role=%v`, x.Role))
} else if x.DB != "" {
x.Role = x.DB
options = append(options, fmt.Sprintf(`--role=%v`, x.DB))
}
if x.Verbose {
options = append(options, "-v")
}
for _, schema := range x.Schemas {
options = append(options, "--schema="+schema)
}
return options
}