Drop unsupported pg_dump options from connection string

This commit is contained in:
Dan Sosedoff
2019-09-25 20:29:21 -05:00
parent d5e4a10137
commit b6f01da232
2 changed files with 44 additions and 4 deletions

View File

@@ -4,19 +4,36 @@ import (
"bytes"
"fmt"
"io"
"net/url"
"os/exec"
"strings"
)
var (
unsupportedDumpOptions = []string{
"search_path",
}
)
// Dump represents a database dump
type Dump struct {
Table string
}
// CanExport returns true if database dump tool could be used without an error
func (d *Dump) CanExport() bool {
err := exec.Command("pg_dump", "--version").Run()
return err == nil
}
func (d *Dump) Export(url string, writer io.Writer) error {
// Export streams the database dump to the specified writer
func (d *Dump) Export(connstr string, writer io.Writer) error {
if str, err := removeUnsupportedOptions(connstr); err != nil {
return err
} else {
connstr = str
}
errOutput := bytes.NewBuffer(nil)
opts := []string{
@@ -29,7 +46,7 @@ func (d *Dump) Export(url string, writer io.Writer) error {
opts = append(opts, []string{"--table", d.Table}...)
}
opts = append(opts, url)
opts = append(opts, connstr)
cmd := exec.Command("pg_dump", opts...)
cmd.Stdout = writer
@@ -40,3 +57,20 @@ func (d *Dump) Export(url string, writer io.Writer) error {
}
return nil
}
// removeUnsupportedOptions removes any options unsupported for making a db dump
func removeUnsupportedOptions(input string) (string, error) {
uri, err := url.Parse(input)
if err != nil {
return "", err
}
q := uri.Query()
for _, opt := range unsupportedDumpOptions {
q.Del(opt)
q.Del(strings.ToUpper(opt))
}
uri.RawQuery = q.Encode()
return uri.String(), nil
}