Skip to content

Commit

Permalink
feat(helper): 数据库分页
Browse files Browse the repository at this point in the history
  • Loading branch information
yeaha committed Sep 15, 2021
1 parent 42499e6 commit 6843d4d
Show file tree
Hide file tree
Showing 2 changed files with 128 additions and 0 deletions.
61 changes: 61 additions & 0 deletions helper.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"context"
"database/sql"
"fmt"
"math"

"github.com/doug-martin/goqu/v9"
"github.com/jmoiron/sqlx"
Expand Down Expand Up @@ -115,3 +116,63 @@ func Transaction(db *sqlx.DB, fn func(tx *sqlx.Tx) error) (err error) {

return fn(tx)
}

// Pagination 数据库分页计算
type Pagination struct {
First int `json:"first"`
Last int `json:"last"`
Previous int `json:"previous"`
Current int `json:"current"`
Next int `json:"next"`
Size int `json:"size"`
Items int `json:"items"`
}

// NewPagination 计算分页页码
func NewPagination(current, size, items int) Pagination {
if current <= 0 {
current = 1
}

p := Pagination{
First: 1,
Last: 1,
Current: current,
}

if size > 0 {
p.Size = size
}
if items > 0 {
p.Items = items
}

if items > 0 && size > 0 {
p.Last = int(math.Ceil(float64(p.Items) / float64(p.Size)))
}

if p.Current < p.First {
p.Current = p.First
} else if p.Current > p.Last {
p.Current = p.Last
}

if p.Current > p.First {
p.Previous = p.Current - 1
}
if p.Current < p.Last {
p.Next = p.Current + 1
}

return p
}

// Limit 数据库查询LIMIT值
func (p Pagination) Limit() int {
return p.Size
}

// Offset 数据库查询OFFSET值
func (p Pagination) Offset() int {
return (p.Current - 1) * p.Size
}
67 changes: 67 additions & 0 deletions helper_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,67 @@
package entity

import (
"reflect"
"testing"
)

func TestPagination(t *testing.T) {
cases := []struct {
Actual Pagination
Excepted Pagination
}{
{
Actual: Pagination{
First: 1,
Last: 1,
Current: 1,
Size: 10,
Items: 0,
},
Excepted: NewPagination(1, 10, 0),
},
{
Actual: Pagination{
First: 1,
Last: 1,
Current: 1,
Size: 10,
Items: 9,
},
Excepted: NewPagination(1, 10, 9),
},
{
Actual: Pagination{
First: 1,
Last: 2,
Current: 1,
Next: 2,
Size: 10,
Items: 11,
},
Excepted: NewPagination(1, 10, 11),
},
{
Actual: Pagination{
First: 1,
Last: 3,
Previous: 1,
Current: 2,
Next: 3,
Size: 10,
Items: 21,
},
Excepted: NewPagination(2, 10, 21),
},
{
Actual: NewPagination(3, 10, 21),
Excepted: NewPagination(4, 10, 21),
},
}

for _, c := range cases {
if !reflect.DeepEqual(c.Actual, c.Excepted) {
t.Fatalf("Pagination, Actual=%+v, Excepted=%+v\n", c.Actual, c.Excepted)
}
}
}

0 comments on commit 6843d4d

Please sign in to comment.