pgweb/pkg/api/api.go

401 lines
7.4 KiB
Go
Raw Normal View History

2015-04-30 19:47:07 +03:00
package api
2014-10-11 02:14:17 +04:00
import (
"encoding/base64"
2014-10-11 02:14:17 +04:00
"errors"
"fmt"
2016-11-06 06:23:26 +03:00
neturl "net/url"
"time"
2014-11-11 08:10:05 +03:00
"github.com/gin-gonic/gin"
2015-04-30 19:47:07 +03:00
"github.com/sosedoff/pgweb/pkg/bookmarks"
"github.com/sosedoff/pgweb/pkg/client"
"github.com/sosedoff/pgweb/pkg/command"
"github.com/sosedoff/pgweb/pkg/connection"
"github.com/sosedoff/pgweb/pkg/shared"
2014-10-11 02:14:17 +04:00
)
var (
DbClient *client.Client
DbSessions = map[string]*client.Client{}
)
func DB(c *gin.Context) *client.Client {
if command.Opts.Sessions {
2016-02-26 19:48:55 +03:00
return DbSessions[getSessionId(c.Request)]
} else {
return DbClient
}
}
func setClient(c *gin.Context, newClient *client.Client) error {
currentClient := DB(c)
if currentClient != nil {
currentClient.Close()
}
if !command.Opts.Sessions {
DbClient = newClient
return nil
}
2016-02-26 19:48:55 +03:00
sessionId := getSessionId(c.Request)
if sessionId == "" {
return errors.New("Session ID is required")
}
DbSessions[sessionId] = newClient
return nil
}
2015-04-30 19:47:07 +03:00
2015-05-01 03:59:48 +03:00
func GetHome(c *gin.Context) {
2015-05-03 04:10:14 +03:00
serveStaticAsset("/index.html", c)
}
2014-10-13 23:40:56 +04:00
2015-05-03 04:10:14 +03:00
func GetAsset(c *gin.Context) {
serveStaticAsset(c.Params.ByName("path"), c)
2014-10-13 22:55:19 +04:00
}
func GetSessions(c *gin.Context) {
// In debug mode endpoint will return a lot of sensitive information
// like full database connection string and all query history.
if command.Opts.Debug {
c.JSON(200, DbSessions)
return
}
c.JSON(200, map[string]int{"sessions": len(DbSessions)})
}
2015-05-03 04:13:04 +03:00
func Connect(c *gin.Context) {
if command.Opts.LockSession {
c.JSON(400, Error{"Session is locked"})
return
}
var sshInfo *shared.SSHInfo
url := c.Request.FormValue("url")
if url == "" {
c.JSON(400, Error{"Url parameter is required"})
return
}
2015-04-30 19:47:07 +03:00
opts := command.Options{Url: url}
url, err := connection.FormatUrl(opts)
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
if c.Request.FormValue("ssh") != "" {
sshInfo = parseSshInfo(c)
}
cl, err := client.NewFromUrl(url, sshInfo)
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
2015-04-30 19:47:07 +03:00
err = cl.Test()
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
2015-04-30 19:47:07 +03:00
info, err := cl.Info()
if err == nil {
err = setClient(c, cl)
if err != nil {
cl.Close()
c.JSON(400, Error{err.Error()})
return
}
}
c.JSON(200, info.Format()[0])
}
2016-11-06 06:23:26 +03:00
func SwitchDb(c *gin.Context) {
if command.Opts.LockSession {
c.JSON(400, Error{"Session is locked"})
return
}
name := c.Request.URL.Query().Get("db")
if name == "" {
name = c.Request.FormValue("db")
}
2016-11-06 06:23:26 +03:00
if name == "" {
c.JSON(400, Error{"Database name is not provided"})
return
}
conn := DB(c)
if conn == nil {
c.JSON(400, Error{"Not connected"})
return
}
currentUrl, err := neturl.Parse(conn.ConnectionString)
if err != nil {
c.JSON(400, Error{"Unable to parse current connection string"})
return
}
2017-01-10 18:14:50 +03:00
currentUrl.Path = name
2016-11-06 06:23:26 +03:00
2017-01-10 18:14:50 +03:00
cl, err := client.NewFromUrl(currentUrl.String(), nil)
2016-11-06 06:23:26 +03:00
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
err = cl.Test()
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
info, err := cl.Info()
if err == nil {
err = setClient(c, cl)
if err != nil {
cl.Close()
c.JSON(400, Error{err.Error()})
return
}
}
conn.Close()
2016-11-06 06:23:26 +03:00
c.JSON(200, info.Format()[0])
}
2016-02-05 08:05:42 +03:00
func Disconnect(c *gin.Context) {
if command.Opts.LockSession {
c.JSON(400, Error{"Session is locked"})
return
}
2016-02-05 08:05:42 +03:00
conn := DB(c)
if conn == nil {
c.JSON(400, Error{"Not connected"})
return
}
err := conn.Close()
if err != nil {
c.JSON(400, Error{err.Error()})
return
}
c.JSON(200, map[string]bool{"success": true})
}
2015-05-03 04:13:04 +03:00
func GetDatabases(c *gin.Context) {
names, err := DB(c).Databases()
2015-05-03 04:32:16 +03:00
serveResult(names, err, c)
2014-10-16 01:05:23 +04:00
}
2016-01-13 06:33:44 +03:00
func GetObjects(c *gin.Context) {
result, err := DB(c).Objects()
if err != nil {
c.JSON(400, NewError(err))
return
}
objects := client.ObjectsFromResult(result)
c.JSON(200, objects)
}
2015-05-03 04:13:04 +03:00
func RunQuery(c *gin.Context) {
query := cleanQuery(c.Request.FormValue("query"))
2014-10-11 02:14:17 +04:00
if query == "" {
c.JSON(400, NewError(errors.New("Query parameter is missing")))
2014-10-11 02:14:17 +04:00
return
}
2015-05-03 04:32:16 +03:00
HandleQuery(query, c)
2014-10-11 02:14:17 +04:00
}
2015-05-03 04:13:04 +03:00
func ExplainQuery(c *gin.Context) {
query := cleanQuery(c.Request.FormValue("query"))
2014-10-11 22:24:12 +04:00
if query == "" {
c.JSON(400, NewError(errors.New("Query parameter is missing")))
2014-10-11 22:24:12 +04:00
return
}
2015-05-03 04:32:16 +03:00
HandleQuery(fmt.Sprintf("EXPLAIN ANALYZE %s", query), c)
2014-10-11 22:24:12 +04:00
}
2015-05-03 04:13:04 +03:00
func GetSchemas(c *gin.Context) {
2016-01-13 06:33:44 +03:00
res, err := DB(c).Schemas()
serveResult(res, err, c)
2014-10-11 02:14:17 +04:00
}
2015-05-03 04:13:04 +03:00
func GetTable(c *gin.Context) {
var res *client.Result
var err error
if c.Request.FormValue("type") == "materialized_view" {
res, err = DB(c).MaterializedView(c.Params.ByName("table"))
} else {
res, err = DB(c).Table(c.Params.ByName("table"))
}
2015-05-03 04:32:16 +03:00
serveResult(res, err, c)
2014-10-11 02:14:17 +04:00
}
2015-05-03 04:13:04 +03:00
func GetTableRows(c *gin.Context) {
offset, err := parseIntFormValue(c, "offset", 0)
if err != nil {
c.JSON(400, NewError(err))
return
}
limit, err := parseIntFormValue(c, "limit", 100)
if err != nil {
c.JSON(400, NewError(err))
return
}
2015-04-30 19:47:07 +03:00
opts := client.RowsOptions{
Limit: limit,
Offset: offset,
SortColumn: c.Request.FormValue("sort_column"),
SortOrder: c.Request.FormValue("sort_order"),
Where: c.Request.FormValue("where"),
}
res, err := DB(c).TableRows(c.Params.ByName("table"), opts)
if err != nil {
c.JSON(400, NewError(err))
return
}
countRes, err := DB(c).TableRowsCount(c.Params.ByName("table"), opts)
if err != nil {
c.JSON(400, NewError(err))
return
}
numFetch := int64(opts.Limit)
numOffset := int64(opts.Offset)
numRows := countRes.Rows[0][0].(int64)
numPages := numRows / numFetch
if numPages*numFetch < numRows {
numPages++
}
res.Pagination = &client.Pagination{
Rows: numRows,
Page: (numOffset / numFetch) + 1,
Pages: numPages,
PerPage: numFetch,
}
2015-05-03 04:32:16 +03:00
serveResult(res, err, c)
}
2015-05-03 04:13:04 +03:00
func GetTableInfo(c *gin.Context) {
res, err := DB(c).TableInfo(c.Params.ByName("table"))
if err != nil {
c.JSON(400, NewError(err))
return
}
c.JSON(200, res.Format()[0])
}
2015-05-01 03:59:48 +03:00
func GetHistory(c *gin.Context) {
c.JSON(200, DB(c).History)
2014-10-11 02:14:17 +04:00
}
2015-05-01 03:59:48 +03:00
func GetConnectionInfo(c *gin.Context) {
res, err := DB(c).Info()
2014-10-11 02:14:17 +04:00
if err != nil {
c.JSON(400, NewError(err))
return
}
info := res.Format()[0]
info["session_lock"] = command.Opts.LockSession
c.JSON(200, info)
2014-10-11 02:14:17 +04:00
}
2015-05-01 03:59:48 +03:00
func GetActivity(c *gin.Context) {
res, err := DB(c).Activity()
2015-05-03 04:32:16 +03:00
serveResult(res, err, c)
}
2015-05-01 03:59:48 +03:00
func GetTableIndexes(c *gin.Context) {
res, err := DB(c).TableIndexes(c.Params.ByName("table"))
2015-05-03 04:32:16 +03:00
serveResult(res, err, c)
2014-10-11 22:20:16 +04:00
}
2015-12-05 03:14:03 +03:00
func GetTableConstraints(c *gin.Context) {
res, err := DB(c).TableConstraints(c.Params.ByName("table"))
2015-12-05 03:14:03 +03:00
serveResult(res, err, c)
}
2015-05-03 04:32:16 +03:00
func HandleQuery(query string, c *gin.Context) {
rawQuery, err := base64.StdEncoding.DecodeString(desanitize64(query))
if err == nil {
query = string(rawQuery)
}
2014-10-11 02:14:17 +04:00
result, err := DB(c).Query(query)
2014-10-11 02:14:17 +04:00
if err != nil {
c.JSON(400, NewError(err))
return
}
format := getQueryParam(c, "format")
filename := getQueryParam(c, "filename")
if filename == "" {
filename = fmt.Sprintf("pgweb-%v.%v", time.Now().Unix(), format)
}
if format != "" {
c.Writer.Header().Set("Content-disposition", "attachment;filename="+filename)
}
switch format {
case "csv":
c.Data(200, "text/csv", result.CSV())
case "json":
c.Data(200, "applicaiton/json", result.JSON())
case "xml":
c.XML(200, result)
default:
c.JSON(200, result)
}
2014-10-11 02:14:17 +04:00
}
2014-10-13 23:40:56 +04:00
2015-05-01 03:59:48 +03:00
func GetBookmarks(c *gin.Context) {
2015-04-30 19:47:07 +03:00
bookmarks, err := bookmarks.ReadAll(bookmarks.Path())
2015-05-03 04:32:16 +03:00
serveResult(bookmarks, err, c)
2014-12-03 07:19:38 +03:00
}
func GetInfo(c *gin.Context) {
info := map[string]string{
"version": command.VERSION,
"git_sha": command.GitCommit,
"build_time": command.BuildTime,
}
c.JSON(200, info)
}