From 9b0b71363f62ebea26d24be6153a78cedc139175 Mon Sep 17 00:00:00 2001 From: Dan Sosedoff Date: Sat, 3 Jan 2015 19:42:56 -0600 Subject: [PATCH] Add /api/:table/rows endpoint to fetch table rows with sorting options --- api.go | 38 ++++++++++++++++++++++++++++++++++++++ client.go | 25 +++++++++++++++++++++++++ 2 files changed, 63 insertions(+) diff --git a/api.go b/api.go index 2ff0511..021a0ce 100644 --- a/api.go +++ b/api.go @@ -5,6 +5,7 @@ import ( "fmt" "mime" "path/filepath" + "strconv" "strings" "github.com/gin-gonic/gin" @@ -52,6 +53,7 @@ func setupRoutes(router *gin.Engine) { api.GET("/connection", API_ConnectionInfo) api.GET("/tables", API_GetTables) api.GET("/tables/:table", API_GetTable) + api.GET("/tables/:table/rows", API_GetTableRows) api.GET("/tables/:table/info", API_GetTableInfo) api.GET("/tables/:table/indexes", API_TableIndexes) api.GET("/query", API_RunQuery) @@ -171,6 +173,42 @@ func API_GetTable(c *gin.Context) { c.JSON(200, res) } +func API_GetTableRows(c *gin.Context) { + limit := 1000 // Number of rows to fetch + limitVal := c.Request.FormValue("limit") + + if limitVal != "" { + num, err := strconv.Atoi(limitVal) + + if err != nil { + c.JSON(400, Error{"Invalid limit value"}) + return + } + + if num <= 0 { + c.JSON(400, Error{"Limit should be greater than 0"}) + return + } + + limit = num + } + + opts := RowsOptions{ + Limit: limit, + SortColumn: c.Request.FormValue("sort_column"), + SortOrder: c.Request.FormValue("sort_order"), + } + + res, err := dbClient.TableRows(c.Params.ByName("table"), opts) + + if err != nil { + c.JSON(400, NewError(err)) + return + } + + c.JSON(200, res) +} + func API_GetTableInfo(c *gin.Context) { res, err := dbClient.TableInfo(c.Params.ByName("table")) diff --git a/client.go b/client.go index 3f8ee17..6fc5854 100644 --- a/client.go +++ b/client.go @@ -22,6 +22,13 @@ type Result struct { Rows []Row `json:"rows"` } +// Struct to hold table rows browsing options +type RowsOptions struct { + Limit int // Number of rows to fetch + SortColumn string // Column to sort by + SortOrder string // Sort direction (ASC, DESC) +} + func NewClient() (*Client, error) { str, err := buildConnectionString(options) @@ -76,6 +83,24 @@ func (client *Client) Table(table string) (*Result, error) { return client.query(PG_TABLE_SCHEMA, table) } +func (client *Client) TableRows(table string, opts RowsOptions) (*Result, error) { + sql := fmt.Sprintf(`SELECT * FROM "%s"`, table) + + if opts.SortColumn != "" { + if opts.SortOrder == "" { + opts.SortOrder = "ASC" + } + + sql += fmt.Sprintf(" ORDER BY %s %s", opts.SortColumn, opts.SortOrder) + } + + if opts.Limit > 0 { + sql += fmt.Sprintf(" LIMIT %d", opts.Limit) + } + + return client.query(sql) +} + func (client *Client) TableInfo(table string) (*Result, error) { return client.query(PG_TABLE_INFO, table) }