Merge pull request #270 from sosedoff/data-export

Database export
This commit is contained in:
Dan Sosedoff
2017-09-19 00:41:04 -05:00
committed by GitHub
6 changed files with 106 additions and 8 deletions

View File

@@ -5,6 +5,7 @@ import (
"errors"
"fmt"
neturl "net/url"
"strings"
"time"
"github.com/gin-gonic/gin"
@@ -398,3 +399,32 @@ func GetInfo(c *gin.Context) {
c.JSON(200, info)
}
// Export database or table data
func DataExport(c *gin.Context) {
db := DB(c)
info, err := db.Info()
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
dump := client.Dump{
Table: strings.TrimSpace(c.Request.FormValue("table")),
}
formattedInfo := info.Format()[0]
filename := formattedInfo["current_database"].(string)
if dump.Table != "" {
filename = filename + "_" + dump.Table
}
attachment := fmt.Sprintf(`attachment; filename="%s.sql.gz"`, filename)
c.Header("Content-Disposition", attachment)
err = dump.Export(db.ConnectionString, c.Writer)
if err != nil {
c.JSON(400, Error{err.Error()})
}
}

View File

@@ -47,5 +47,6 @@ func SetupRoutes(router *gin.Engine) {
api.POST("/explain", ExplainQuery)
api.GET("/history", GetHistory)
api.GET("/bookmarks", GetBookmarks)
api.GET("/export", DataExport)
}
}

37
pkg/client/dump.go Normal file
View File

@@ -0,0 +1,37 @@
package client
import (
"bytes"
"fmt"
"io"
"os/exec"
)
type Dump struct {
Table string
}
func (d *Dump) Export(url string, writer io.Writer) error {
errOutput := bytes.NewBuffer(nil)
opts := []string{
"--no-owner", // skip restoration of object ownership in plain-text format
"--clean", // clean (drop) database objects before recreating
"--compress", "6", // compression level for compressed formats
}
if d.Table != "" {
opts = append(opts, []string{"--table", d.Table}...)
}
opts = append(opts, url)
cmd := exec.Command("pg_dump", opts...)
cmd.Stdout = writer
cmd.Stderr = errOutput
if err := cmd.Run(); err != nil {
return fmt.Errorf("error: %s. output: %s", err.Error(), errOutput.Bytes())
}
return nil
}

File diff suppressed because one or more lines are too long