diff --git a/common/paginate.go b/common/paginate.go index a175fc4..e2fb946 100644 --- a/common/paginate.go +++ b/common/paginate.go @@ -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) } diff --git a/common/paginate_test.go b/common/paginate_test.go new file mode 100644 index 0000000..d1390f3 --- /dev/null +++ b/common/paginate_test.go @@ -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) + } + } +} diff --git a/common/where_test.go b/common/where_test.go index 144f05f..9e5c2c8 100644 --- a/common/where_test.go +++ b/common/where_test.go @@ -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",