Implement pagination and simple filtering

This commit is contained in:
Dan Sosedoff
2016-01-08 14:16:53 -06:00
parent 61523e33df
commit 38c971ab49
8 changed files with 390 additions and 28 deletions

View File

@@ -125,9 +125,37 @@ func GetTableRows(c *gin.Context) {
Offset: offset,
SortColumn: c.Request.FormValue("sort_column"),
SortOrder: c.Request.FormValue("sort_order"),
Where: c.Request.FormValue("where"),
}
res, err := DbClient.TableRows(c.Params.ByName("table"), opts)
if err != nil {
c.JSON(400, NewError(err))
return
}
countRes, err := DbClient.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,
}
serveResult(res, err, c)
}

View File

@@ -47,7 +47,7 @@ func parseIntFormValue(c *gin.Context, name string, defValue int) (int, error) {
return defValue, fmt.Errorf("%s must be a number", name)
}
if num < 1 {
if num < 1 && defValue != 0 {
return defValue, fmt.Errorf("%s must be greated than 0", name)
}

View File

@@ -21,6 +21,7 @@ type Client struct {
// Struct to hold table rows browsing options
type RowsOptions struct {
Where string // Custom filter
Offset int // Number of rows to skip
Limit int // Number of rows to fetch
SortColumn string // Column to sort by
@@ -99,6 +100,10 @@ func (client *Client) Table(table string) (*Result, error) {
func (client *Client) TableRows(table string, opts RowsOptions) (*Result, error) {
sql := fmt.Sprintf(`SELECT * FROM "%s"`, table)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
}
if opts.SortColumn != "" {
if opts.SortOrder == "" {
opts.SortOrder = "ASC"
@@ -118,6 +123,16 @@ func (client *Client) TableRows(table string, opts RowsOptions) (*Result, error)
return client.query(sql)
}
func (client *Client) TableRowsCount(table string, opts RowsOptions) (*Result, error) {
sql := fmt.Sprintf(`SELECT COUNT(1) FROM "%s"`, table)
if opts.Where != "" {
sql += fmt.Sprintf(" WHERE %s", opts.Where)
}
return client.query(sql)
}
func (client *Client) TableInfo(table string) (*Result, error) {
return client.query(statements.PG_TABLE_INFO, table)
}

View File

@@ -11,9 +11,17 @@ import (
type Row []interface{}
type Pagination struct {
Rows int64 `json:"rows_count"`
Page int64 `json:"page"`
Pages int64 `json:"pages_count"`
PerPage int64 `json:"per_page"`
}
type Result struct {
Columns []string `json:"columns"`
Rows []Row `json:"rows"`
Pagination *Pagination `json:"pagination,omitempty"`
Columns []string `json:"columns"`
Rows []Row `json:"rows"`
}
// Due to big int number limitations in javascript, numbers should be encoded

File diff suppressed because one or more lines are too long