github.com/aacfactory/fns-contrib/databases/sql@v1.2.84/dac/page.go (about) 1 package dac 2 3 import ( 4 "github.com/aacfactory/errors" 5 "github.com/aacfactory/fns-contrib/databases/sql/dac/specifications" 6 "github.com/aacfactory/fns/context" 7 "math" 8 ) 9 10 type Pager[T Table] struct { 11 // No 12 // @title no 13 // @description no of page 14 No int `json:"no"` 15 // Pages 16 // @title pages 17 // @description total pages 18 Pages int64 `json:"pages"` 19 // Total 20 // @title total 21 // @description total entries 22 Total int64 `json:"total"` 23 // Entries 24 // @title entries 25 // @description entries of page 26 Entries []T `json:"entries"` 27 } 28 29 func Page[T Table](ctx context.Context, no int, size int, options ...QueryOption) (page Pager[T], err error) { 30 opt := QueryOptions{} 31 for _, option := range options { 32 option(&opt) 33 } 34 35 count, countErr := Count[T](ctx, opt.cond) 36 if countErr != nil { 37 err = errors.Warning("sql: page failed").WithCause(countErr) 38 return 39 } 40 if count == 0 { 41 page = Pager[T]{ 42 No: 0, 43 Pages: 0, 44 Total: 0, 45 Entries: nil, 46 } 47 return 48 } 49 50 rng := specifications.PG(no, size).Range() 51 entries, queryErr := Query[T](ctx, rng.Offset, rng.Length, options...) 52 if queryErr != nil { 53 err = errors.Warning("sql: page failed").WithCause(queryErr) 54 return 55 } 56 57 page = Pager[T]{ 58 No: no, 59 Pages: int64(math.Ceil(float64(count) / float64(size))), 60 Total: count, 61 Entries: entries, 62 } 63 return 64 }