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

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