Merge pull request #441 from sosedoff/drop-pg-dump-params

Drop unsupported pg_dump options from connection string
This commit is contained in:
Dan Sosedoff 2019-09-25 20:39:55 -05:00 committed by GitHub
commit c4db1973c4
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
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
}

View File

@ -34,8 +34,8 @@ func testDumpExport(t *testing.T) {
assert.NoError(t, err)
// Test nonexistent database
invalidUrl := fmt.Sprintf("postgres://%s@%s:%s/%s?sslmode=disable", serverUser, serverHost, serverPort, "foobar")
err = dump.Export(invalidUrl, saveFile)
invalidURL := fmt.Sprintf("postgres://%s@%s:%s/%s?sslmode=disable", serverUser, serverHost, serverPort, "foobar")
err = dump.Export(invalidURL, saveFile)
assert.Contains(t, err.Error(), `database "foobar" does not exist`)
// Test dump of non existent db
@ -43,4 +43,10 @@ func testDumpExport(t *testing.T) {
err = dump.Export(url, saveFile)
assert.NotNil(t, err)
assert.Contains(t, err.Error(), "pg_dump: no matching tables were found")
// Should drop "search_path" param from URI
dump = Dump{}
searchPathURL := fmt.Sprintf("postgres://%s@%s:%s/%s?sslmode=disable&search_path=private", serverUser, serverHost, serverPort, serverDatabase)
err = dump.Export(searchPathURL, saveFile)
assert.NoError(t, err)
}