map的分页

This commit is contained in:
xing 2023-02-26 21:55:03 +08:00
parent 9c89f44841
commit b4cc570e8a
2 changed files with 99 additions and 7 deletions

View File

@ -10,6 +10,9 @@ import (
)
func pagination[T Model](db dbQuery, ctx context.Context, q QueryCondition) (r []T, total int, err error) {
if q.Page < 1 {
return
}
qx := QueryCondition{
Where: q.Where,
Having: q.Having,
@ -46,14 +49,42 @@ func pagination[T Model](db dbQuery, ctx context.Context, q QueryCondition) (r [
return
}
q.Offset = offset
sq, args, err := BuildQuerySql[T](q)
if err != nil {
m := ctx.Value("handle=>")
if m != nil {
mm, ok := m.(string)
if ok && mm == "toMap" {
v := ctx.Value("map")
mx, er := findToStringMap[T](db, ctx, q)
if er != nil {
err = er
return
}
err = db.Select(ctx, &r, sq, args...)
if err != nil {
vv := v.(*[]map[string]string)
*vv = mx
return
}
}
r, err = finds[T](db, ctx, q)
return
}
func paginationToMap[T Model](db dbQuery, ctx context.Context, q QueryCondition) (r []map[string]string, total int, err error) {
ctx = context.WithValue(ctx, "handle=>", "toMap")
ctx = context.WithValue(ctx, "map", &r)
_, total, err = pagination[T](db, ctx, q)
return
}
func PaginationToMap[T Model](ctx context.Context, q QueryCondition) (r []map[string]string, total int, err error) {
ctx = context.WithValue(ctx, "handle=>", "toMap")
ctx = context.WithValue(ctx, "map", &r)
_, total, err = pagination[T](globalBb, ctx, q)
return
}
func PaginationToMapFromDB[T Model](db dbQuery, ctx context.Context, q QueryCondition) (r []map[string]string, total int, err error) {
ctx = context.WithValue(ctx, "handle=>", "toMap")
ctx = context.WithValue(ctx, "map", &r)
_, total, err = pagination[T](db, ctx, q)
return
}

View File

@ -516,3 +516,64 @@ func Test_pagination(t *testing.T) {
})
}
}
func Test_paginationToMap(t *testing.T) {
type args struct {
db dbQuery
ctx context.Context
q QueryCondition
}
tests := []struct {
name string
args args
wantR []map[string]string
wantTotal int
wantErr bool
}{
{
name: "t1",
args: args{
db: glob,
ctx: ctx,
q: QueryCondition{
Fields: "ID",
Limit: 2,
Page: 1,
Where: SqlBuilder{{"ID < 200"}},
},
},
wantR: []map[string]string{{"ID": "63"}, {"ID": "64"}},
wantTotal: 4,
},
{
name: "t2",
args: args{
db: glob,
ctx: ctx,
q: QueryCondition{
Fields: "ID",
Limit: 2,
Page: 2,
Where: SqlBuilder{{"ID < 200"}},
},
},
wantR: []map[string]string{{"ID": "190"}, {"ID": "193"}},
wantTotal: 4,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
gotR, gotTotal, err := paginationToMap[post](tt.args.db, tt.args.ctx, tt.args.q)
if (err != nil) != tt.wantErr {
t.Errorf("paginationToMap() error = %v, wantErr %v", err, tt.wantErr)
return
}
if !reflect.DeepEqual(gotR, tt.wantR) {
t.Errorf("paginationToMap() gotR = %v, want %v", gotR, tt.wantR)
}
if gotTotal != tt.wantTotal {
t.Errorf("paginationToMap() gotTotal = %v, want %v", gotTotal, tt.wantTotal)
}
})
}
}