From dc04b8dc2b1c0f50d9b42e82205d5933f00c5f64 Mon Sep 17 00:00:00 2001 From: xing Date: Thu, 2 Feb 2023 13:19:43 +0800 Subject: [PATCH] =?UTF-8?q?=E7=AE=80=E5=8C=96=E7=89=88=20pagination?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- model/querycondition.go | 9 +++++- model/querycondition_test.go | 57 ++++++++++++++++++++++++++++++++++++ 2 files changed, 65 insertions(+), 1 deletion(-) diff --git a/model/querycondition.go b/model/querycondition.go index 1976754..33f0484 100644 --- a/model/querycondition.go +++ b/model/querycondition.go @@ -7,7 +7,7 @@ import ( "strings" ) -// Finds can use offset +// Finds 比 Find 多一个offset // // Conditions 中可用 Where Fields Group Having Join Order Offset Limit In 函数 func Finds[T Model](ctx context.Context, q *QueryCondition) (r []T, err error) { @@ -132,3 +132,10 @@ func Chunk[T Model, R any](ctx context.Context, perLimit int, fn func(rows T) (R } return } + +// Pagination 同 SimplePagination +// +// Condition 中可使用 Where Fields Group Having Join Order Page Limit In 函数 +func Pagination[T Model](ctx context.Context, q *QueryCondition) ([]T, int, error) { + return SimplePagination[T](ctx, q.where, q.fields, q.group, q.page, q.limit, q.order, q.join, q.having, q.in...) +} diff --git a/model/querycondition_test.go b/model/querycondition_test.go index 2cabfb0..9829844 100644 --- a/model/querycondition_test.go +++ b/model/querycondition_test.go @@ -2,6 +2,7 @@ package model import ( "context" + "database/sql" "github.com/fthvgb1/wp-go/helper/number" "github.com/fthvgb1/wp-go/helper/slice" "reflect" @@ -173,3 +174,59 @@ func TestChunk(t *testing.T) { }) } } + +func TestPagination(t *testing.T) { + type args struct { + ctx context.Context + q *QueryCondition + } + type testCase[T Model] struct { + name string + args args + want []T + want1 int + wantErr bool + } + tests := []testCase[post]{ + { + name: "t1", + args: args{ + ctx: ctx, + q: Conditions( + Where(SqlBuilder{ + {"ID", "in", ""}, + }), + Page(1), + Limit(5), + In([][]any{slice.ToAnySlice(number.Range(431, 440, 1))}...), + ), + }, + want: func() (r []post) { + r, err := Select[post](ctx, "select * from "+post{}.Table()+" where ID in (?,?,?,?,?)", slice.ToAnySlice(number.Range(431, 435, 1))...) + if err != nil && err != sql.ErrNoRows { + panic(err) + } else if err == sql.ErrNoRows { + err = nil + } + return + }(), + want1: 10, + wantErr: false, + }, + } + for _, tt := range tests { + t.Run(tt.name, func(t *testing.T) { + got, got1, err := Pagination[post](tt.args.ctx, tt.args.q) + if (err != nil) != tt.wantErr { + t.Errorf("Pagination() error = %v, wantErr %v", err, tt.wantErr) + return + } + if !reflect.DeepEqual(got, tt.want) { + t.Errorf("Pagination() got = %v, want %v", got, tt.want) + } + if got1 != tt.want1 { + t.Errorf("Pagination() got1 = %v, want %v", got1, tt.want1) + } + }) + } +}