-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpagination.go
More file actions
541 lines (476 loc) · 14.4 KB
/
pagination.go
File metadata and controls
541 lines (476 loc) · 14.4 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
package pagination
import (
"context"
"fmt"
"reflect"
"strings"
"github.com/getevo/evo/v2"
"github.com/getevo/evo/v2/lib/outcome"
"github.com/getevo/evo/v2/lib/ptr"
"gorm.io/gorm"
)
const (
defaultSize = 10
defaultMaxSize = 50
defaultPageRangeSize = 5
)
// ParamNames holds the HTTP query-parameter names used by New.
// Leave any field empty to keep its default value.
type ParamNames struct {
Page string // default "page"
Size string // default "size"
Sort string // default "sort"
Order string // default "order"
}
func (n ParamNames) page() string {
if n.Page != "" {
return n.Page
}
return "page"
}
func (n ParamNames) size() string {
if n.Size != "" {
return n.Size
}
return "size"
}
func (n ParamNames) sort() string {
if n.Sort != "" {
return n.Sort
}
return "sort"
}
func (n ParamNames) order() string {
if n.Order != "" {
return n.Order
}
return "order"
}
// Options configures pagination behaviour.
type Options struct {
// Size is the default page size when the ?size query param is absent (default 10).
Size int `json:"size"`
// Page is the default page number when the ?page query param is absent (default 1).
Page int `json:"page"`
// MaxSize is the maximum allowed page size. Requests for a larger size are clamped
// to this value (default 50). Must be > 0.
MaxSize int `json:"max_size"`
// PageRangeSize controls how many page numbers appear in PageRange (default 5).
PageRangeSize int `json:"page_range_size"`
// Debug enables GORM SQL logging for the underlying queries.
Debug bool `json:"debug"`
// SkipCount skips the COUNT(*) query for better performance on large tables.
// Records and Pages will be -1 in the response.
// HasNext is inferred from whether the result set fills a full page.
// Note: LinkHeader is not generated when SkipCount is true.
SkipCount bool `json:"skip_count"`
// SortFields is an allowlist of column names that callers may sort via
// ?sort=field&order=asc|desc query params.
// Multi-column sort is supported: ?sort=name,created_at&order=asc,desc
// If empty, sort/order query params are ignored (SQL injection prevention).
SortFields []string `json:"sort_fields,omitempty"`
// UseScan uses gorm Scan instead of Find when populating the output.
// Required for custom projection structs that don't match the model type.
UseScan bool `json:"use_scan"`
// ParamNames overrides the HTTP query-parameter names used by New.
// Leave zero to use the defaults (page, size, sort, order).
ParamNames ParamNames `json:"param_names,omitempty"`
// BaseURL is used to generate RFC 5988 Link headers via LinkHeader().
// When set, GetResponse() automatically adds the Link header to the response.
// Example: "https://api.example.com/orders"
// Link headers are not generated when SkipCount is true.
BaseURL string `json:"base_url,omitempty"`
}
// Pagination holds the pagination state and the response payload.
type Pagination struct {
Model *gorm.DB `json:"-"`
Executed bool `json:"-"`
Debug bool `json:"-"`
// internal
skipCount bool
useScan bool
sortFields map[string]bool
pageRangeSize int
baseURL string
Success bool `json:"success"`
Error *string `json:"error,omitempty"`
Records int `json:"records"` // Total rows (-1 when SkipCount is true)
CurrentPage int `json:"current_page"` // Current page (1-indexed)
Pages int `json:"pages"` // Total pages (-1 when SkipCount is true)
Size int `json:"size"` // Records per page
MaxSize int `json:"max_size"` // Maximum allowed page size
First int `json:"first"` // 1-indexed position of the first record on this page
Last int `json:"last"` // 1-indexed position of the last record on this page
HasNext bool `json:"has_next"` // True when a next page exists
HasPrev bool `json:"has_prev"` // True when a previous page exists
PageRange []int `json:"page_range"` // Visible page numbers centered around CurrentPage
Data any `json:"data"`
}
// SetMaxSize updates the maximum page size and clamps the current size if needed.
// Non-positive values are ignored to prevent LIMIT 0 / full-table-scan security issues.
func (p *Pagination) SetMaxSize(limit int) {
if limit <= 0 {
return
}
p.MaxSize = limit
if p.Size > limit {
p.Size = limit
}
}
// GetOffset returns the SQL OFFSET value for the current page.
func (p *Pagination) GetOffset() int {
return (p.GetPage() - 1) * p.Size
}
// GetPage returns the current page number (minimum 1).
func (p *Pagination) GetPage() int {
if p.CurrentPage < 1 {
p.CurrentPage = 1
}
return p.CurrentPage
}
// LinkHeader returns an RFC 5988 Link header value for the current pagination state.
// Returns an empty string when BaseURL was not set or SkipCount is true (total unknown).
// The header includes rel="first", rel="last", rel="prev" (if applicable), and rel="next"
// (if applicable).
func (p *Pagination) LinkHeader() string {
if p.baseURL == "" || p.Pages <= 0 {
return ""
}
sep := "?"
if strings.Contains(p.baseURL, "?") {
sep = "&"
}
url := func(page int) string {
return fmt.Sprintf("<%s%spage=%d&size=%d>", p.baseURL, sep, page, p.Size)
}
parts := []string{
url(1) + `; rel="first"`,
url(p.Pages) + `; rel="last"`,
}
if p.HasPrev {
parts = append(parts, url(p.CurrentPage-1)+`; rel="prev"`)
}
if p.HasNext {
parts = append(parts, url(p.CurrentPage+1)+`; rel="next"`)
}
return strings.Join(parts, ", ")
}
// New creates a Pagination instance driven by HTTP query parameters.
// Query params: ?page=N&size=N&sort=column&order=asc|desc
// Multi-column sort: ?sort=name,created_at&order=asc,desc
//
// Priority: query param > Options field > built-in default.
// The request context is propagated to all database queries.
func New(model *gorm.DB, request *evo.Request, out any, options ...Options) (*Pagination, error) {
var opt Options
if len(options) > 0 {
opt = options[0]
}
pn := opt.ParamNames
// Start from Options defaults, then let query params override.
size := opt.Size
page := opt.Page
if qSize := request.Query(pn.size()).Int(); qSize > 0 {
size = qSize
}
if qPage := request.Query(pn.page()).Int(); qPage > 0 {
page = qPage
}
p := newPagination(model, size, page, opt)
// Propagate request context so DB queries are cancelled if the client disconnects.
p.Model = p.Model.WithContext(request.Context.Context())
// Apply sort/order from query params only if the field is in the allowlist.
if len(p.sortFields) > 0 {
sortParam := request.Query(pn.sort()).String()
orderParam := request.Query(pn.order()).String()
if clause := buildOrderClause(sortParam, orderParam, p.sortFields); clause != "" {
p.Model = p.Model.Order(clause)
}
}
return p.LoadData(out)
}
// NewWithContext creates a Pagination instance with an explicit context.
// Use this when you have a context but no *evo.Request (e.g. background jobs, gRPC handlers).
func NewWithContext(ctx context.Context, model *gorm.DB, page, size int, out any, options ...Options) (*Pagination, error) {
var opt Options
if len(options) > 0 {
opt = options[0]
}
if page <= 0 {
page = opt.Page
}
if size <= 0 {
size = opt.Size
}
p := newPagination(model, size, page, opt)
p.Model = p.Model.WithContext(ctx)
return p.LoadData(out)
}
// NewFromParams creates a Pagination instance from explicit parameters.
// Useful for testing or non-HTTP contexts where no *evo.Request is available.
//
// Priority: page/size args > Options field > built-in default.
func NewFromParams(model *gorm.DB, page, size int, out any, options ...Options) (*Pagination, error) {
var opt Options
if len(options) > 0 {
opt = options[0]
}
if page <= 0 {
page = opt.Page
}
if size <= 0 {
size = opt.Size
}
p := newPagination(model, size, page, opt)
return p.LoadData(out)
}
// newPagination initialises a Pagination with normalised size/page/maxSize values.
func newPagination(model *gorm.DB, size, page int, opt Options) *Pagination {
maxSize := opt.MaxSize
if maxSize <= 0 {
maxSize = defaultMaxSize
}
if size <= 0 {
size = defaultSize
}
if size > maxSize {
size = maxSize
}
if page < 1 {
page = 1
}
prs := opt.PageRangeSize
if prs <= 0 {
prs = defaultPageRangeSize
}
// Build sort allowlist map for O(1) lookup.
allowed := make(map[string]bool, len(opt.SortFields))
for _, f := range opt.SortFields {
allowed[f] = true
}
return &Pagination{
Model: model,
Debug: opt.Debug,
skipCount: opt.SkipCount,
useScan: opt.UseScan,
sortFields: allowed,
pageRangeSize: prs,
baseURL: opt.BaseURL,
Size: size,
MaxSize: maxSize,
CurrentPage: page,
}
}
// buildOrderClause builds a safe ORDER BY clause from comma-separated sort/order params.
// Each column is checked against the allowlist; unknown columns are silently skipped.
// Example: sort="name,created_at" order="asc,desc" → "name asc, created_at desc"
func buildOrderClause(sortParam, orderParam string, allowed map[string]bool) string {
if sortParam == "" {
return ""
}
cols := strings.Split(sortParam, ",")
orders := strings.Split(orderParam, ",")
var parts []string
for i, col := range cols {
col = strings.TrimSpace(col)
if !allowed[col] {
continue
}
ord := "asc"
if i < len(orders) {
o := strings.ToLower(strings.TrimSpace(orders[i]))
if o == "desc" {
ord = "desc"
}
}
parts = append(parts, col+" "+ord)
}
return strings.Join(parts, ", ")
}
// computeMeta derives all response fields that depend on Records and Size.
// Must be called after Records and Size are finalised.
func (p *Pagination) computeMeta() {
if p.Records <= 0 {
p.Pages = 1
p.First = 0
p.Last = 0
p.HasNext = false
p.HasPrev = false
p.PageRange = []int{1}
return
}
// Total pages (ceiling division).
p.Pages = (p.Records + p.Size - 1) / p.Size
if p.Pages == 0 {
p.Pages = 1
}
// Clamp current page to valid range.
if p.CurrentPage < 1 {
p.CurrentPage = 1
}
if p.CurrentPage > p.Pages {
p.CurrentPage = p.Pages
}
// First/Last record numbers on this page (1-indexed).
p.First = (p.CurrentPage-1)*p.Size + 1
p.Last = p.CurrentPage * p.Size
if p.Last > p.Records {
p.Last = p.Records
}
// Navigation helpers.
p.HasPrev = p.CurrentPage > 1
p.HasNext = p.CurrentPage < p.Pages
// Visible page window centered on CurrentPage.
p.PageRange = computePageRange(p.CurrentPage, p.Pages, p.pageRangeSize)
}
// computePageRange returns up to `window` page numbers centered on `current`.
func computePageRange(current, total, window int) []int {
if total <= 0 {
return []int{1}
}
half := window / 2
start := current - half
end := start + window - 1
if start < 1 {
start = 1
end = window
}
if end > total {
end = total
start = end - window + 1
if start < 1 {
start = 1
}
}
pages := make([]int, 0, end-start+1)
for i := start; i <= end; i++ {
pages = append(pages, i)
}
return pages
}
// LoadData executes the count and data queries and populates out.
// out must be a non-nil pointer to a slice (e.g. *[]User).
func (p *Pagination) LoadData(out any) (*Pagination, error) {
// Validate that out is a non-nil pointer to a slice before touching the DB.
if err := validateSlicePtr(out); err != nil {
p.Error = ptr.String(err.Error())
return p, err
}
if p.Debug {
p.Model = p.Model.Debug()
}
if p.skipCount {
// Skip COUNT — Records and Pages are unknown.
p.Records = -1
p.Pages = -1
p.First = p.GetOffset() + 1
p.HasPrev = p.CurrentPage > 1
} else {
var total int64
// Use Session to isolate COUNT from any SELECT/DISTINCT/GROUP clauses already
// on the statement, preventing incorrect counts on complex queries.
if err := p.Model.Session(&gorm.Session{}).Count(&total).Error; err != nil {
p.Error = ptr.String(err.Error())
return p, err
}
p.Records = int(total)
p.computeMeta()
// Skip the data query entirely when there are no matching records.
if p.Records == 0 {
p.Executed = true
p.Success = true
p.Data = derefSlice(out)
return p, nil
}
}
q := p.Model.Limit(p.Size).Offset(p.GetOffset())
var dbErr error
if p.useScan {
dbErr = q.Scan(out).Error
} else {
dbErr = q.Find(out).Error
}
if dbErr != nil {
p.Error = ptr.String("unable to load data from the database")
return p, dbErr
}
// When SkipCount is true, infer HasNext from result length.
if p.skipCount {
n := sliceLen(out)
p.Last = p.GetOffset() + n
p.HasNext = n == p.Size
// Correct First to 0 when the page returned no results.
if n == 0 {
p.First = 0
}
}
p.Executed = true
p.Success = true
// Store the dereferenced slice (not the pointer) for clean JSON serialisation:
// an empty result renders as [] rather than null.
p.Data = derefSlice(out)
return p, nil
}
// validateSlicePtr returns an error if v is not a non-nil pointer to a slice.
func validateSlicePtr(v any) error {
if v == nil {
return fmt.Errorf("pagination: out must be a pointer to a slice, got nil")
}
rv := reflect.ValueOf(v)
if rv.Kind() != reflect.Ptr {
return fmt.Errorf("pagination: out must be a pointer to a slice, got %T", v)
}
if rv.IsNil() {
return fmt.Errorf("pagination: out must be a non-nil pointer to a slice, got nil %T", v)
}
if rv.Elem().Kind() != reflect.Slice {
return fmt.Errorf("pagination: out must be a pointer to a slice, got pointer to %s", rv.Elem().Kind())
}
return nil
}
// derefSlice dereferences a pointer-to-slice so the slice value is stored in Data.
// A nil slice is promoted to an empty initialised slice so JSON always renders []
// instead of null. Non-pointer / non-slice values are returned unchanged.
func derefSlice(v any) any {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return nil
}
rv = rv.Elem()
}
if rv.Kind() == reflect.Slice {
if rv.IsNil() {
return reflect.MakeSlice(rv.Type(), 0, 0).Interface()
}
return rv.Interface()
}
return v
}
// sliceLen returns the length of a slice behind an any/interface{} pointer.
// Returns 0 safely for nil pointers.
func sliceLen(v any) int {
rv := reflect.ValueOf(v)
for rv.Kind() == reflect.Ptr {
if rv.IsNil() {
return 0
}
rv = rv.Elem()
}
if rv.Kind() == reflect.Slice {
return rv.Len()
}
return 0
}
// GetResponse implements outcome.HTTPSerializer.
// When BaseURL is set, a RFC 5988 Link header is automatically included.
func (p *Pagination) GetResponse() outcome.Response {
if p.Success {
r := outcome.OK(p)
if link := p.LinkHeader(); link != "" {
r = r.Header("Link", link)
}
return *r
}
return *outcome.InternalServerError(p)
}