-
Notifications
You must be signed in to change notification settings - Fork 7
Expand file tree
/
Copy pathpage.go
More file actions
341 lines (295 loc) · 7.87 KB
/
Copy pathpage.go
File metadata and controls
341 lines (295 loc) · 7.87 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
package pgkit
import (
"cmp"
"context"
"regexp"
"slices"
"strings"
sq "github.com/Masterminds/squirrel"
"github.com/jackc/pgx/v5"
)
const (
// DefaultPageSize is the default number of rows per page.
DefaultPageSize = 10
// MaxPageSize is the maximum number of rows per page.
MaxPageSize = 50
)
type Order string
const (
Desc Order = "DESC"
Asc Order = "ASC"
)
// PageKind classifies a Page by the fields it carries. It is validation input
// for Table.ListPaged, not a mode selector — the table's Mode picks the path.
type PageKind uint8
const (
EmptyPage PageKind = iota // neither a cursor nor an explicit page number
OffsetPage // an explicit page number (Page > 1), no cursor
CursorPage // a cursor, no page number
MixedPage // both a cursor and a page number — always invalid
)
// Kind classifies the page by its populated fields.
func (p *Page) Kind() PageKind {
if p == nil {
return EmptyPage
}
hasCursor, hasPage := p.Cursor != "", p.Page > 1
switch {
case hasCursor && hasPage:
return MixedPage
case hasCursor:
return CursorPage
case hasPage:
return OffsetPage
default:
return EmptyPage
}
}
// IsValid reports whether o is one of the defined sort directions.
func (o Order) IsValid() bool {
return o == Asc || o == Desc
}
// Sanitize normalizes case and surrounding whitespace, defaulting any unrecognized value to Asc.
func (o Order) Sanitize() Order {
o = Order(strings.ToUpper(strings.TrimSpace(string(o))))
if !o.IsValid() {
return Asc
}
return o
}
type Sort struct {
Column string
Order Order
}
func (s Sort) sanitize(columnFunc func(string) string) Sort {
s.Column = strings.TrimSpace(s.Column)
if s.Column != "" {
if columnFunc != nil {
s.Column = columnFunc(s.Column)
}
s.Column = pgx.Identifier(strings.Split(s.Column, ".")).Sanitize()
}
s.Order = s.Order.Sanitize()
return s
}
func (s Sort) String() string {
s = s.sanitize(nil)
if s.Column == "" {
return ""
}
return s.Column + " " + string(s.Order)
}
var _MatcherOrderBy = regexp.MustCompile(`-?([a-zA-Z0-9]+)`)
func NewSort(s string) (Sort, bool) {
s = strings.TrimSpace(s)
if s == "" || !_MatcherOrderBy.MatchString(s) {
return Sort{}, false
}
sort := Sort{
Column: s,
Order: Asc,
}
if strings.HasPrefix(s, "-") {
sort.Column = s[1:]
sort.Order = Desc
}
return sort, true
}
type Page struct {
Size uint32
Page uint32
More bool
Column string
Sort []Sort
// Unused by the offset Paginator — shared here so callers can swap paginators without changing the Page type.
Cursor string
NextCursor string
}
func NewPage(size, page uint32, sort ...Sort) *Page {
return &Page{
Size: size,
Page: page,
Sort: sort,
}
}
func (p *Page) SetDefaults(o *PaginatorSettings) {
if o == nil {
o = &PaginatorSettings{}
}
defaultSize := cmp.Or(o.DefaultSize, DefaultPageSize)
maxSize := cmp.Or(o.MaxSize, MaxPageSize)
p.Size = cmp.Or(p.Size, defaultSize)
if p.Size > maxSize {
p.Size = maxSize
}
p.Page = cmp.Or(p.Page, 1)
}
func (p *Page) GetOrder(columnFunc func(string) string, defaultSort ...string) []Sort {
var sorts []Sort
if p != nil && len(p.Sort) != 0 {
sorts = slices.Clone(p.Sort)
}
// fall back to column
if len(sorts) == 0 {
if p != nil && p.Column != "" {
for part := range strings.SplitSeq(p.Column, ",") {
if s, ok := NewSort(part); ok {
sorts = append(sorts, s)
}
}
}
}
if len(sorts) == 0 {
for _, s := range defaultSort {
if s, ok := NewSort(s); ok {
sorts = append(sorts, s)
}
}
}
for i := range sorts {
sorts[i] = sorts[i].sanitize(columnFunc)
}
return sorts
}
func (p *Page) Offset() uint64 {
n := uint64(1)
if p != nil && p.Page != 0 {
n = uint64(p.Page)
}
if n < 1 {
n = 1
}
return (n - 1) * p.Limit()
}
func (p *Page) Limit() uint64 {
n := uint64(DefaultPageSize)
if p != nil && p.Size != 0 {
n = uint64(p.Size)
}
return n
}
// PaginatorSettings are the settings for the paginator.
type PaginatorSettings struct {
// DefaultSize is the default number of rows per page.
// If zero, DefaultPageSize is used.
DefaultSize uint32
// MaxSize is the maximum number of rows per page.
// If zero, MaxPageSize is used. If less than DefaultSize, it is set to DefaultSize.
MaxSize uint32
// Sort is the default sort order.
Sort []string
// ColumnFunc is a transformation applied to column names.
ColumnFunc func(string) string
}
type PaginatorOption func(*PaginatorSettings)
// WithDefaultSize sets the default page size.
func WithDefaultSize(size uint32) PaginatorOption {
return func(s *PaginatorSettings) {
s.DefaultSize = size
}
}
// WithMaxSize sets the maximum page size.
func WithMaxSize(size uint32) PaginatorOption {
return func(s *PaginatorSettings) {
s.MaxSize = size
}
}
// WithSort sets the default sort order.
func WithSort(sort ...string) PaginatorOption {
return func(s *PaginatorSettings) {
s.Sort = sort
}
}
// WithColumnFunc sets a function to transform column names.
func WithColumnFunc(f func(string) string) PaginatorOption {
return func(s *PaginatorSettings) {
s.ColumnFunc = f
}
}
// NewPaginator creates a new paginator with the given options.
// If MaxSize is less than DefaultSize, MaxSize is set to DefaultSize.
func NewPaginator[T any](options ...PaginatorOption) Paginator[T] {
settings := &PaginatorSettings{
DefaultSize: DefaultPageSize,
MaxSize: MaxPageSize,
}
for _, option := range options {
option(settings)
}
if settings.MaxSize < settings.DefaultSize {
settings.MaxSize = settings.DefaultSize
}
return Paginator[T]{settings: *settings}
}
// Paginator is a helper to paginate results.
type Paginator[T any] struct {
settings PaginatorSettings
}
func (p Paginator[T]) getOrder(page *Page) []string {
sort := page.GetOrder(p.settings.ColumnFunc, p.settings.Sort...)
list := make([]string, len(sort))
for i := range sort {
list[i] = sort[i].Column + " " + string(sort[i].Order)
}
return list
}
// PrepareQuery adds pagination to the query. It sets the number of max rows to limit+1.
func (p Paginator[T]) PrepareQuery(q sq.SelectBuilder, page *Page) ([]T, sq.SelectBuilder) {
if page == nil {
page = &Page{}
}
page.SetDefaults(&p.settings)
limit := page.Limit()
q = q.Limit(limit + 1).Offset(page.Offset()).OrderBy(p.getOrder(page)...)
return make([]T, 0, limit+1), q
}
// Paginate returns offset-paginated rows and the page populated with More.
func (p Paginator[T]) Paginate(ctx context.Context, query *Querier, q sq.SelectBuilder, page *Page) ([]T, *Page, error) {
if page == nil {
page = &Page{}
}
result, q := p.PrepareQuery(q, page)
if err := query.GetAll(ctx, q, &result); err != nil {
return nil, nil, err
}
return p.PrepareResult(result, page), page, nil
}
func (p Paginator[T]) PrepareRaw(q string, args []any, page *Page) ([]T, string, []any) {
if page == nil {
page = &Page{}
}
page.SetDefaults(&p.settings)
limit, offset := page.Limit(), page.Offset()
if order := p.getOrder(page); len(order) > 0 {
q = q + " ORDER BY " + strings.Join(order, ", ")
}
q = q + " LIMIT @limit OFFSET @offset"
injected := false
for _, arg := range args {
if existing, ok := arg.(pgx.NamedArgs); ok {
existing["limit"] = limit + 1
existing["offset"] = offset
injected = true
break
}
}
if !injected {
args = append(args, pgx.NamedArgs{"limit": limit + 1, "offset": offset})
}
return make([]T, 0, limit+1), q, args
}
// PrepareResult prepares the paginated result. If the number of rows is n+1:
// - it removes the last element, returning n elements
// - it sets more to true in the page object
func (p Paginator[T]) PrepareResult(result []T, page *Page) []T {
limit := int(page.Limit())
page.More = len(result) > limit
// Offset pagination yields no cursor - clear any stale value from a reused page.
page.NextCursor = ""
if page.More {
result = result[:limit]
}
page.Size = uint32(limit)
page.Page = 1 + uint32(page.Offset())/uint32(limit)
return result
}