-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathutils.go
89 lines (72 loc) · 1.99 KB
/
utils.go
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
package query
import "strconv"
const (
defaultPagingLimit = 1000
)
// PaginateQuery returns a paginated query string for the given input options.
//
// The input query string is expected as follows:
// "SELECT ... WHERE (...)" <- these brackets are not optional
//
// The output query string would be as follows:
// "SELECT ... WHERE (...) AND id > ? ORDER BY ? LIMIT ?"
// -or-
// "SELECT ... WHERE (...) AND id < ? ORDER BY ? LIMIT ?"
//
// Example:
// query := "SELECT * FROM table WHERE (state = $1 OR age > $2)"
//
// opts := []interface{}{ state: 123, age: 45, }
// cursor := 123
// limit := 10
// direction := Ascending
//
// PaginateQuery(query, opts, cursor, limit, direction)
// > "SELECT * FROM table WHERE (state = $1 OR age > $2) AND cursor > $3 ORDER BY id ASC LIMIT 10"
func PaginateQuery(query string, opts []interface{},
cursor Cursor, limit uint64, direction Ordering) (string, []interface{}) {
if len(cursor) > 0 {
v := strconv.Itoa(len(opts) + 1)
if direction == Ascending {
query += " AND id > $" + v
} else {
query += " AND id < $" + v
}
opts = append(opts, cursor.ToUint64())
}
if direction == Ascending {
query += " ORDER BY id ASC"
} else {
query += " ORDER BY id DESC"
}
if limit > 0 {
v := strconv.Itoa(len(opts) + 1)
query += " LIMIT $" + v
opts = append(opts, limit)
}
return query, opts
}
func DefaultPaginationHandler(opts ...Option) (*QueryOptions, error) {
req := QueryOptions{
Limit: defaultPagingLimit,
SortBy: Ascending,
Supported: CanLimitResults | CanSortBy | CanQueryByCursor,
}
req.Apply(opts...)
if req.Limit > defaultPagingLimit {
return nil, ErrQueryNotSupported
}
return &req, nil
}
func DefaultPaginationHandlerWithLimit(limit uint64, opts ...Option) (*QueryOptions, error) {
req := QueryOptions{
Limit: limit,
SortBy: Ascending,
Supported: CanLimitResults | CanSortBy | CanQueryByCursor,
}
req.Apply(opts...)
if req.Limit > limit {
return nil, ErrQueryNotSupported
}
return &req, nil
}