Fix some pagination memes

This commit is contained in:
Howl 2016-11-21 16:27:21 +01:00
parent 7a65b705d6
commit 78a1c1d038
3 changed files with 64 additions and 34 deletions

View File

@ -1,42 +1,22 @@
package common
import (
"fmt"
"strconv"
)
import "fmt"
// Paginate creates an additional SQL LIMIT clause for paginating.
func Paginate(page, limit string, maxLimit int) string {
var (
pInt int
lInt int
err error
p = Int(page)
l = Int(limit)
)
if page == "" {
pInt = 1
} else {
pInt, err = strconv.Atoi(page)
if err != nil {
pInt = 1
}
if p < 1 {
p = 1
}
if limit == "" {
lInt = 50
} else {
lInt, err = strconv.Atoi(limit)
if err != nil {
lInt = 50
}
if l < 1 {
l = 50
}
if pInt < 1 {
pInt = 1
if l > maxLimit {
l = maxLimit
}
if lInt < 1 {
lInt = 50
}
if lInt > maxLimit {
lInt = maxLimit
}
start := (pInt - 1) * lInt
return fmt.Sprintf(" LIMIT %d,%d ", start, lInt)
start := uint(p-1) * uint(l)
return fmt.Sprintf(" LIMIT %d,%d ", start, l)
}

49
common/paginate_test.go Normal file
View File

@ -0,0 +1,49 @@
package common
import "testing"
func TestPaginate(t *testing.T) {
type args struct {
page string
limit string
maxLimit int
}
tests := []struct {
name string
args args
want string
}{
{
"1",
args{
"10",
"",
100,
},
" LIMIT 450,50 ",
},
{
"2",
args{
"-5",
"-15",
100,
},
" LIMIT 0,50 ",
},
{
"3",
args{
"2",
"150",
100,
},
" LIMIT 100,100 ",
},
}
for _, tt := range tests {
if got := Paginate(tt.args.page, tt.args.limit, tt.args.maxLimit); got != tt.want {
t.Errorf("%q. Paginate() = %v, want %v", tt.name, got, tt.want)
}
}
}

View File

@ -41,7 +41,7 @@ func TestWhereClause_In(t *testing.T) {
"simple",
&WhereClause{},
args{"users.id", []string{"1", "2", "3"}},
&WhereClause{"WHERE users.id IN (?, ?, ?)", []interface{}{"1", "2", "3"}},
&WhereClause{"WHERE users.id IN (?, ?, ?)", []interface{}{"1", "2", "3"}, false},
},
{
"withExisting",
@ -50,6 +50,7 @@ func TestWhereClause_In(t *testing.T) {
&WhereClause{
"WHERE users.username = ? AND users.xd > ? AND users.id IN (?)",
[]interface{}{"Howl", "6", "1"},
false,
},
},
}
@ -75,12 +76,12 @@ func TestWhere(t *testing.T) {
{
"simple",
args{"users.id = ?", "5", nil},
&WhereClause{"WHERE users.id = ?", []interface{}{"5"}},
&WhereClause{"WHERE users.id = ?", []interface{}{"5"}, false},
},
{
"allowed",
args{"users.id = ?", "5", []string{"1", "3", "5"}},
&WhereClause{"WHERE users.id = ?", []interface{}{"5"}},
&WhereClause{"WHERE users.id = ?", []interface{}{"5"}, false},
},
{
"notAllowed",