-
Notifications
You must be signed in to change notification settings - Fork 0
/
query_builder.go
441 lines (377 loc) · 11.6 KB
/
query_builder.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
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
package pagefilter
import (
"errors"
"fmt"
"net/http"
"reflect"
"strings"
"github.com/jmoiron/sqlx"
)
var (
// ErrNoDestination is returned when the destination is nil
ErrNoDestination = errors.New("destination is nil")
)
// Paginator is the struct that provides the paging.
type Paginator struct {
db DB
idKey string
table string
filter Filter
details *PaginatorDetails
}
// NewPaginator creates a new paginator
func NewPaginator(db DB, table, idk string, f Filter) *Paginator {
if f == nil {
f = NewMultiFilter()
}
return &Paginator{
db: db,
idKey: idk,
table: table,
filter: f,
}
}
// ParseRequest parses the request to handle retrieving all the pagination and sorting parameters
func (p *Paginator) ParseRequest(req *http.Request, sortColumns ...string) error {
pd, err := DetailsFromRequest(req)
if err != nil {
return err
}
return p.SetDetails(pd, sortColumns...)
}
// DetailsFromRequest retrieves the paginator details from the request.
func DetailsFromRequest(req *http.Request) (*PaginatorDetails, error) {
q := req.URL.Query()
limit, err := getLimit(q)
if err != nil {
return nil, fmt.Errorf("%v: %w", err, ErrInvalidPaginatorDetails)
}
return &PaginatorDetails{
Limit: limit,
LastVal: q.Get(QueryLastVal),
LastID: q.Get(QueryLastID),
SortBy: q.Get(QuerySortBy),
SortDir: q.Get(QuerySortDir),
}, nil
}
// SetDetails sets paginator details from the passed in arguments.
func (p *Paginator) SetDetails(paginatorDetails *PaginatorDetails, sortColumns ...string) error {
p.details = paginatorDetails
wantedSort := p.details.SortBy
p.details.SortBy = ""
if wantedSort != "" {
for _, v := range sortColumns {
if v == wantedSort {
p.details.SortBy = v
break
}
}
if p.details.SortBy == "" {
return fmt.Errorf("invalid sort %q", wantedSort)
}
}
if p.details.SortBy == "" {
// We have no specified sort so use the id key
p.details.SortBy = p.idKey
}
sort := strings.ToLower(p.details.SortDir)
// Define sql from constants to ensure sql query / user input separation
switch sort {
case "", orderAsc:
p.details.sortComparator = sqlComparatorAsc
p.details.sortOperator = sqlOperatorAsc
case orderDesc:
p.details.sortComparator = sqlComparatorDesc
p.details.sortOperator = sqlOperatorDesc
default:
return fmt.Errorf("invalid sort direction %q", sort)
}
return nil
}
// First is used when no details are provided which could give us the pivot point
// It will pick a start depending on the provided sort and filters.
func (p *Paginator) First() (string, error) {
jSQL, jArgs := p.filter.Join()
wSQL, wArgs := p.filter.Where()
var gSQL string
if g, ok := p.filter.(Grouper); ok && len(g.Group()) > 0 {
gSQL = fmt.Sprintf("GROUP BY %s", strings.Join(g.Group(), ", "))
}
// Be aware of SQL injection if modifying the below SQL. Any parameters in the sprintf
// MUST not be allowed to be created by external input.
sqlBuilder := new(strings.Builder)
sqlBuilder.WriteString("SELECT t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" \n")
sqlBuilder.WriteString("FROM ")
sqlBuilder.WriteString(p.table)
sqlBuilder.WriteString(" t \n")
if jSQL != "" {
sqlBuilder.WriteString(jSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("WHERE (1 = 1) \n")
if wSQL != "" {
sqlBuilder.WriteString("AND (\n")
sqlBuilder.WriteString(trimWherePrefix(wSQL))
sqlBuilder.WriteString("\n)\n")
}
if gSQL != "" {
sqlBuilder.WriteString(gSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("ORDER BY t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" ")
sqlBuilder.WriteString(p.details.sortComparator)
sqlBuilder.WriteString(", t.")
sqlBuilder.WriteString(p.idKey)
sqlBuilder.WriteString(" ASC \n")
sqlBuilder.WriteString("LIMIT 1")
args := append(jArgs, wArgs...)
var err error
sql := sqlBuilder.String()
sql, args, err = sqlx.In(sql, args...)
if err != nil {
return "", fmt.Errorf("first sql in: %w", err)
}
var pivot string
err = p.db.Get(&pivot, sql, args...)
if err != nil {
return "", fmt.Errorf("first select: %w", err)
}
return pivot, nil
}
// Pivot finds the pivot point in the data.
func (p *Paginator) Pivot() (string, error) {
// We were given no information about where to pivot from, pivot from the first value
if p.details.LastID == "" && p.details.LastVal == "" {
return p.First()
}
jSQL, jArgs := p.filter.Join()
wSQL, wArgs := p.filter.Where()
var gSQL string
if g, ok := p.filter.(Grouper); ok && len(g.Group()) > 0 {
gSQL = fmt.Sprintf("GROUP BY %s", strings.Join(g.Group(), ", "))
}
// Be aware of SQL injection if modifying the below SQL. Any parameters in the sprintf
// MUST not be allowed to be created by external input.
sqlBuilder := new(strings.Builder)
sqlBuilder.WriteString("SELECT t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" \n")
sqlBuilder.WriteString("FROM ")
sqlBuilder.WriteString(p.table)
sqlBuilder.WriteString(" t \n")
if jSQL != "" {
sqlBuilder.WriteString(jSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("WHERE (t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" = ? AND t.")
sqlBuilder.WriteString(p.idKey)
sqlBuilder.WriteString(" >= ?) \n")
if wSQL != "" {
sqlBuilder.WriteString("AND (\n")
sqlBuilder.WriteString(trimWherePrefix(wSQL))
sqlBuilder.WriteString("\n)\n")
}
if gSQL != "" {
sqlBuilder.WriteString(gSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("LIMIT 1")
args := append(jArgs, p.details.LastVal, p.details.LastID)
args = append(args, wArgs...)
sql := sqlBuilder.String()
var err error
sql, args, err = sqlx.In(sql, args...)
if err != nil {
return "", fmt.Errorf("pivot sql in: %w", err)
}
var pivot string
err = p.db.Get(&pivot, sql, args...)
if err != nil {
return "", fmt.Errorf("pivot select: %w", err)
}
return pivot, nil
}
// Retrieve pulls the next page given the pivot point and requires a destination *[]struct to load the data into.
func (p *Paginator) Retrieve(pivot string, dest any) error {
if dest == nil {
return ErrNoDestination
}
// Gracefully locate all the columns to load.
t := reflect.TypeOf(dest)
if t.Kind() != reflect.Ptr {
return fmt.Errorf("unexpected type %s (expected pointer)", t.Kind())
}
t = t.Elem()
if t.Kind() != reflect.Slice {
return fmt.Errorf("unexpected type %s (expected slice)", t.Kind())
}
elemType := t.Elem()
if elemType.Kind() == reflect.Ptr {
elemType = elemType.Elem()
}
if elemType.Kind() != reflect.Struct {
return fmt.Errorf("unexpected type %s (expected struct)", elemType.Kind())
}
cols := new(strings.Builder)
for i := 0; i < elemType.NumField(); i++ {
field := elemType.Field(i)
dbTag := field.Tag.Get("db")
switch dbTag {
case "":
dbTag = strings.ToLower(field.Name)
case "-":
continue
}
if cols.Len() > 0 {
cols.WriteString(", ")
}
// If the db tag contains "autoinc" or "pk" then we need to use the first part of the db tag
// as the column name and the second part as the alias. This is because the db tag is used to
// generate the SQL query and the SQL query must be valid.
//
// e.g. `db:"id,autoinc,pk"` will generate "t.id 'id'" in the SQL query
if structTags := strings.Split(dbTag, ","); len(structTags) > 1 {
for _, tag := range structTags {
switch tag {
case dbTagAutoIncrement:
dbTag = strings.ReplaceAll(dbTag, ","+dbTagAutoIncrement, "")
case dbTagPrimaryKey:
dbTag = strings.ReplaceAll(dbTag, ","+dbTagPrimaryKey, "")
case dbTagDefault:
dbTag = strings.ReplaceAll(dbTag, ","+dbTagDefault, "")
}
}
}
// In order for our db tag to remain compatible with the sql db tag mapper
// we must use commas as separators. However, we want everything after the first comma to be
// one argument, as the arbitrary SQL there may itself contain commas, hence the SplitN
args := strings.SplitN(dbTag, ",", 2)
switch len(args) {
case 1:
if len(strings.Split(args[0], ".")) == 2 {
cols.WriteString(args[0] + " '" + args[0] + "'")
} else {
cols.WriteString("t." + args[0])
}
case 2:
cols.WriteString(args[1] + " '" + args[0] + "'")
}
}
jSQL, jArgs := p.filter.Join()
wSQL, wArgs := p.filter.Where()
var gSQL string
if g, ok := p.filter.(Grouper); ok && len(g.Group()) > 0 {
gSQL = fmt.Sprintf("GROUP BY %s", strings.Join(g.Group(), ", "))
}
// Be aware of SQL injection if modifying the below SQL. Any parameters in the sprintf
// MUST not be allowed to be created by external input.
sqlBuilder := new(strings.Builder)
sqlBuilder.WriteString("SELECT ")
sqlBuilder.WriteString(cols.String())
sqlBuilder.WriteString(" \n")
sqlBuilder.WriteString("FROM ")
sqlBuilder.WriteString(p.table)
sqlBuilder.WriteString(" t \n")
if jSQL != "" {
sqlBuilder.WriteString(jSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("WHERE (t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" ")
sqlBuilder.WriteString(p.details.sortOperator)
sqlBuilder.WriteString(" ? OR (t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" = ? AND t.")
sqlBuilder.WriteString(p.idKey)
sqlBuilder.WriteString(" > ?)) \n")
if wSQL != "" {
sqlBuilder.WriteString("AND (\n")
sqlBuilder.WriteString(trimWherePrefix(wSQL))
sqlBuilder.WriteString("\n)\n")
}
if gSQL != "" {
sqlBuilder.WriteString(gSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("ORDER BY t.")
sqlBuilder.WriteString(p.details.SortBy)
sqlBuilder.WriteString(" ")
sqlBuilder.WriteString(p.details.sortComparator)
sqlBuilder.WriteString(", t.")
sqlBuilder.WriteString(p.idKey)
sqlBuilder.WriteString(" ASC \n")
args := append(jArgs, pivot, pivot, p.details.LastID)
args = append(args, wArgs...)
if p.details.Limit > 0 {
sqlBuilder.WriteString("LIMIT ?")
args = append(args, p.details.Limit)
}
sql := sqlBuilder.String()
var err error
sql, args, err = sqlx.In(sql, args...)
if err != nil {
return fmt.Errorf("retrieve sql in: %w", err)
}
err = p.db.Select(dest, sql, args...)
if err != nil {
return fmt.Errorf("retrieve select: %w", err)
}
return nil
}
// Counts returns the total number of records in the table given the provided filters. This does not take into
// account of the current pivot or limit.
func (p *Paginator) Counts(dest *int64) error {
jSQL, jArgs := p.filter.Join()
wSQL, wArgs := p.filter.Where()
var gSQL string
if g, ok := p.filter.(Grouper); ok && len(g.Group()) > 0 {
gSQL = fmt.Sprintf("GROUP BY %s", strings.Join(g.Group(), ", "))
}
// Be aware of SQL injection if modifying the below SQL. Any parameters in the sprintf
// MUST not be allowed to be created by external input.
sqlBuilder := new(strings.Builder)
sqlBuilder.WriteString("SELECT COUNT(*) \n")
sqlBuilder.WriteString("FROM ")
sqlBuilder.WriteString(p.table)
sqlBuilder.WriteString(" t \n")
if jSQL != "" {
sqlBuilder.WriteString(jSQL)
sqlBuilder.WriteString(" \n")
}
sqlBuilder.WriteString("WHERE (1=1) \n")
if wSQL != "" {
sqlBuilder.WriteString("AND (\n")
sqlBuilder.WriteString(trimWherePrefix(wSQL))
sqlBuilder.WriteString("\n)\n")
}
if gSQL != "" {
sqlBuilder.WriteString(gSQL)
sqlBuilder.WriteString(" \n")
}
sql := sqlBuilder.String()
args := append(jArgs, wArgs...)
var err error
sql, args, err = sqlx.In(sql, args...)
if err != nil {
return fmt.Errorf("counts sql in: %w", err)
}
err = p.db.Get(dest, sql, args...)
if err != nil {
return fmt.Errorf("counts select: %w", err)
}
return nil
}
func trimWherePrefix(w string) string {
if strings.HasPrefix(w, string(WhereTypeAnd)) || strings.HasPrefix(w, string(WhereTypeOr)) {
w = strings.TrimPrefix(w, string(WhereTypeAnd))
w = strings.TrimPrefix(w, string(WhereTypeOr))
}
return strings.TrimSpace(w)
}