-
Notifications
You must be signed in to change notification settings - Fork 7
feat: CursorPaginator for keyset pagination #55
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
8 commits
Select commit
Hold shift + click to select a range
4002347
feat: CursorPaginator for keyset pagination
klaidliadon 3240682
refactor: bind cursor behavior to the cursor type via interface
klaidliadon 7f30c0a
refactor(cursor): early-return PrepareResult on the no-more branch
klaidliadon afa154f
fix(cursor): bind order to cursor contract
klaidliadon f6ebd4a
fix(cursor): reject page-level ordering
klaidliadon 59eff68
fix(cursor): allow matching page order
klaidliadon 412d4ee
fix(cursor): add list helper returning page
klaidliadon 77a9953
fix(cursor): rename list helper to paginate
klaidliadon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,153 @@ | ||
| package pgkit | ||
|
|
||
| import ( | ||
| "context" | ||
| "encoding/base64" | ||
| "encoding/json" | ||
| "errors" | ||
| "fmt" | ||
|
|
||
| sq "github.com/Masterminds/squirrel" | ||
| "github.com/lann/builder" | ||
| ) | ||
|
|
||
| var ( | ||
| // ErrInvalidCursor signals a client-supplied cursor that failed to decode - map to 400, not 500. | ||
| ErrInvalidCursor = errors.New("invalid cursor") | ||
| // ErrCursorQueryOrdered signals a cursor-paginated query that already had ORDER BY. | ||
| ErrCursorQueryOrdered = errors.New("cursor query already has order by") | ||
| // ErrCursorPageOrdered signals page-level ordering that does not match the cursor order. | ||
| ErrCursorPageOrdered = errors.New("cursor page order does not match cursor order") | ||
| ) | ||
|
|
||
| // EncodeCursor produces an opaque cursor: base64-JSON, not signed, never use it for authorization. | ||
| func EncodeCursor[C any](cursor C) (string, error) { | ||
| raw, err := json.Marshal(cursor) | ||
| if err != nil { | ||
| return "", fmt.Errorf("marshal cursor: %w", err) | ||
| } | ||
| return base64.RawURLEncoding.EncodeToString(raw), nil | ||
| } | ||
|
|
||
| // DecodeCursor returns (nil, nil) for empty input so callers can compose with a nil-check. | ||
| func DecodeCursor[C any](value string) (*C, error) { | ||
| if value == "" { | ||
| return nil, nil | ||
| } | ||
| raw, err := base64.RawURLEncoding.DecodeString(value) | ||
| if err != nil { | ||
| return nil, ErrInvalidCursor | ||
| } | ||
| var cursor C | ||
| if err := json.Unmarshal(raw, &cursor); err != nil { | ||
| return nil, ErrInvalidCursor | ||
| } | ||
| return &cursor, nil | ||
| } | ||
|
|
||
| // Cursor is the interface a typed keyset cursor satisfies — mirrors pgkit.Record[T, I]'s self-pointer pattern. | ||
| type Cursor[Self any, Row any] interface { | ||
| PtrTo[Self] | ||
| Apply(sq.SelectBuilder) sq.SelectBuilder | ||
| From(Row) error | ||
| // OrderBy must match Apply and should include a unique tiebreaker. | ||
| OrderBy() []Sort | ||
| } | ||
|
|
||
| // CursorPaginator is the keyset sibling of Paginator[T] for ordering-stable pagination under concurrent writes. | ||
| type CursorPaginator[T any, C any, PC Cursor[C, T]] struct { | ||
| settings PaginatorSettings | ||
| } | ||
|
|
||
| // NewCursorPaginator honors only size options - the cursor owns ORDER BY. | ||
| func NewCursorPaginator[T any, C any, PC Cursor[C, T]](options ...PaginatorOption) CursorPaginator[T, C, PC] { | ||
| settings := &PaginatorSettings{ | ||
| DefaultSize: DefaultPageSize, | ||
| MaxSize: MaxPageSize, | ||
| } | ||
| for _, option := range options { | ||
| option(settings) | ||
| } | ||
| if settings.MaxSize < settings.DefaultSize { | ||
| settings.MaxSize = settings.DefaultSize | ||
| } | ||
| return CursorPaginator[T, C, PC]{settings: *settings} | ||
| } | ||
|
|
||
| // PrepareQuery chains LIMIT n+1 so PrepareResult can detect a next page without a second round-trip. | ||
| func (p CursorPaginator[T, C, PC]) PrepareQuery(q sq.SelectBuilder, page *Page) ([]T, sq.SelectBuilder, error) { | ||
| if page == nil { | ||
| page = &Page{} | ||
| } | ||
| page.SetDefaults(&p.settings) | ||
|
|
||
| if _, ok := builder.Get(q, "OrderByParts"); ok { | ||
| return nil, q, ErrCursorQueryOrdered | ||
| } | ||
| var zero C | ||
| order := PC(&zero).OrderBy() | ||
| pageOrder := page.GetOrder(nil) | ||
| if len(pageOrder) != 0 && len(pageOrder) != len(order) { | ||
| return nil, q, ErrCursorPageOrdered | ||
| } | ||
| for i := range pageOrder { | ||
| if pageOrder[i] != order[i].sanitize(nil) { | ||
| return nil, q, ErrCursorPageOrdered | ||
| } | ||
| } | ||
| for _, sort := range order { | ||
| q = q.OrderBy(sort.String()) | ||
| } | ||
| if page.Cursor != "" { | ||
| cursor, err := DecodeCursor[C](page.Cursor) | ||
| if err != nil { | ||
| return nil, q, err | ||
| } | ||
| q = PC(cursor).Apply(q) | ||
| } | ||
|
|
||
| limit := page.Limit() | ||
| q = q.Limit(limit + 1) | ||
| return make([]T, 0, limit+1), q, nil | ||
| } | ||
|
|
||
| // Paginate returns cursor-paginated rows and the page populated with More and NextCursor. | ||
| func (p CursorPaginator[T, C, PC]) Paginate(ctx context.Context, query *Querier, q sq.SelectBuilder, page *Page) ([]T, *Page, error) { | ||
| if page == nil { | ||
| page = &Page{} | ||
| } | ||
| result, q, err := p.PrepareQuery(q, page) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| if err := query.GetAll(ctx, q, &result); err != nil { | ||
| return nil, nil, err | ||
| } | ||
| result, err = p.PrepareResult(result, page) | ||
| if err != nil { | ||
| return nil, nil, err | ||
| } | ||
| return result, page, nil | ||
| } | ||
|
|
||
| // PrepareResult must be called after GetAll to populate page.More and page.NextCursor. | ||
| func (p CursorPaginator[T, C, PC]) PrepareResult(result []T, page *Page) ([]T, error) { | ||
| limit := int(page.Limit()) | ||
| page.Size = uint32(limit) | ||
| page.More = len(result) > limit | ||
| if !page.More { | ||
| return result, nil | ||
| } | ||
| result = result[:limit] | ||
|
|
||
| var cursor C | ||
| if err := PC(&cursor).From(result[len(result)-1]); err != nil { | ||
| return nil, fmt.Errorf("cursor from row: %w", err) | ||
| } | ||
| next, err := EncodeCursor(cursor) | ||
| if err != nil { | ||
| return nil, err | ||
| } | ||
| page.NextCursor = next | ||
| return result, nil | ||
| } | ||
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.