-
Notifications
You must be signed in to change notification settings - Fork 23
/
Copy pathmain.go
943 lines (794 loc) · 18.6 KB
/
main.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
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
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
package rqp
import (
"fmt"
"net/url"
"strconv"
"strings"
"github.com/pkg/errors"
)
// Query the main struct of package
type Query struct {
query map[string][]string
validations Validations
Fields []string
Offset int
Limit int
Sorts []Sort
Filters []*Filter
delimiterIN string
delimiterOR string
ignoreUnknown bool
Error error
}
// Method is a compare method type
type Method string
// Compare methods:
var (
EQ Method = "EQ"
NE Method = "NE"
GT Method = "GT"
LT Method = "LT"
GTE Method = "GTE"
LTE Method = "LTE"
LIKE Method = "LIKE"
ILIKE Method = "ILIKE"
NLIKE Method = "NLIKE"
NILIKE Method = "NILIKE"
IS Method = "IS"
NOT Method = "NOT"
IN Method = "IN"
NIN Method = "NIN"
raw Method = "raw" // internal usage
)
// NULL constant
const NULL = "NULL"
var (
translateMethods map[Method]string = map[Method]string{
EQ: "=",
NE: "!=",
GT: ">",
LT: "<",
GTE: ">=",
LTE: "<=",
LIKE: "LIKE",
ILIKE: "ILIKE",
NLIKE: "NOT LIKE",
NILIKE: "NOT ILIKE",
IS: "IS",
NOT: "IS NOT",
IN: "IN",
NIN: "NOT IN",
}
)
// Sort is ordering struct
type Sort struct {
By string
Desc bool
}
// IgnoreUnknownFilters set behavior for Parser to raise ErrFilterNotAllowed to undefined filters or not
func (q *Query) IgnoreUnknownFilters(i bool) *Query {
q.ignoreUnknown = i
return q
}
// SetDelimiterIN sets delimiter for values of filters
func (q *Query) SetDelimiterIN(d string) *Query {
q.delimiterIN = d
return q
}
// SetDelimiterOR sets delimiter for OR filters in query part of URL
func (q *Query) SetDelimiterOR(d string) *Query {
q.delimiterOR = d
return q
}
// FieldsString returns elements list separated by comma (",") for querying in SELECT statement or a star ("*") if nothing provided
//
// Return example:
//
// When "fields" empty or not provided: `*`.
//
// When "fields=id,email": `id, email`.
//
func (q *Query) FieldsString() string {
if len(q.Fields) == 0 {
return "*"
}
return strings.Join(q.Fields, ", ")
}
// Select returns elements list separated by comma (",") for querying in SELECT statement or a star ("*") if nothing provided
//
// Return examples:
//
// When "fields" empty or not provided: `*`
//
// When "fields=id,email": `id, email`
//
func (q *Query) Select() string {
if len(q.Fields) == 0 {
return "*"
}
return strings.Join(q.Fields, ", ")
}
// SELECT returns word SELECT with fields from Filter "fields" separated by comma (",") from URL-Query
// or word SELECT with star ("*") if nothing provided
//
// Return examples:
//
// When "fields" empty or not provided: `SELECT *`.
//
// When "fields=id,email": `SELECT id, email`.
//
func (q *Query) SELECT() string {
if len(q.Fields) == 0 {
return "SELECT *"
}
return fmt.Sprintf("SELECT %s", q.FieldsString())
}
// HaveField returns true if request asks for specified field
func (q *Query) HaveField(field string) bool {
return stringInSlice(field, q.Fields)
}
// AddField adds field to SELECT statement
func (q *Query) AddField(field string) *Query {
q.Fields = append(q.Fields, field)
return q
}
// OFFSET returns word OFFSET with number
//
// Return example: ` OFFSET 0`
//
func (q *Query) OFFSET() string {
if q.Offset > 0 {
return fmt.Sprintf(" OFFSET %d", q.Offset)
}
return ""
}
// LIMIT returns word LIMIT with number
//
// Return example: ` LIMIT 100`
//
func (q *Query) LIMIT() string {
if q.Limit > 0 {
return fmt.Sprintf(" LIMIT %d", q.Limit)
}
return ""
}
// Order returns list of elements for ORDER BY statement
// you can use +/- prefix to specify direction of sorting (+ is default)
// return example: `id DESC, email`
func (q *Query) Order() string {
if len(q.Sorts) == 0 {
return ""
}
var s string
for i := 0; i < len(q.Sorts); i++ {
if i > 0 {
s += ", "
}
if q.Sorts[i].Desc {
s += fmt.Sprintf("%s DESC", q.Sorts[i].By)
} else {
s += q.Sorts[i].By
}
}
return s
}
// ORDER returns words ORDER BY with list of elements for sorting
// you can use +/- prefix to specify direction of sorting (+ is default, apsent is +)
//
// Return example: ` ORDER BY id DESC, email`
func (q *Query) ORDER() string {
if len(q.Sorts) == 0 {
return ""
}
return fmt.Sprintf(" ORDER BY %s", q.Order())
}
// HaveSortBy returns true if request contains sorting by specified in by field name
func (q *Query) HaveSortBy(by string) bool {
for _, v := range q.Sorts {
if v.By == by {
return true
}
}
return false
}
// AddSortBy adds an ordering rule to Query
func (q *Query) AddSortBy(by string, desc bool) *Query {
q.Sorts = append(q.Sorts, Sort{
By: by,
Desc: desc,
})
return q
}
// HaveFilter returns true if request contains some filter
func (q *Query) HaveFilter(name string) bool {
for _, v := range q.Filters {
if v.Name == name {
return true
}
}
return false
}
// AddFilter adds a filter to Query
func (q *Query) AddFilter(name string, m Method, value interface{}) *Query {
q.Filters = append(q.Filters, &Filter{
Name: name,
Method: m,
Value: value,
})
return q
}
// AddORFilters adds multiple filter into one `OR` statement inside parenteses.
// E.g. (firstname ILIKE ? OR lastname ILIKE ?)
func (q *Query) AddORFilters(fn func(query *Query)) *Query {
_q := New()
fn(_q)
if len(_q.Filters) < 2 {
return q
}
firstIdx := 0
lastIdx := len(_q.Filters) - 1
for i := 0; i < len(_q.Filters); i++ {
switch i {
case firstIdx:
_q.Filters[i].OR = StartOR
case lastIdx:
_q.Filters[i].OR = EndOR
default:
_q.Filters[i].OR = InOR
}
}
q.Filters = append(q.Filters, _q.Filters...)
return q
}
// AddFilterRaw adds a filter to Query as SQL condition.
// This function supports only single condition per one call.
// If you'd like add more then one conditions you should call this func several times.
func (q *Query) AddFilterRaw(condition string) *Query {
q.Filters = append(q.Filters, &Filter{
Name: condition,
Method: raw,
})
return q
}
// RemoveFilter removes the filter by name
func (q *Query) RemoveFilter(name string) error {
var found bool
for i := 0; i < len(q.Filters); i++ {
v := q.Filters[i]
// set next and previous Filter
var next, prev *Filter
if i+1 < len(q.Filters) {
next = q.Filters[i+1]
} else {
next = nil
}
if i-1 >= 0 {
prev = q.Filters[i-1]
} else {
prev = nil
}
if v.Name == name {
// special cases for removing filters in OR statement
if v.OR == StartOR && next != nil {
if next.OR == EndOR {
next.OR = NoOR
} else {
next.OR = StartOR
}
} else if v.OR == EndOR && prev != nil {
if prev.OR == StartOR {
prev.OR = NoOR
} else {
prev.OR = EndOR
}
}
// safe remove element from slice
if i < len(q.Filters)-1 {
copy(q.Filters[i:], q.Filters[i+1:])
}
q.Filters[len(q.Filters)-1] = nil
q.Filters = q.Filters[:len(q.Filters)-1]
found = true
i--
}
}
if !found {
return ErrFilterNotFound
}
return nil
}
// AddValidation adds a validation to Query
func (q *Query) AddValidation(NameAndTags string, v ValidationFunc) *Query {
if q.validations == nil {
q.validations = Validations{}
}
q.validations[NameAndTags] = v
return q
}
// RemoveValidation remove a validation from Query
// You can provide full name of filter with tags or only name of filter:
// RemoveValidation("id:int") and RemoveValidation("id") are equal
func (q *Query) RemoveValidation(NameAndOrTags string) error {
for k := range q.validations {
if k == NameAndOrTags {
delete(q.validations, k)
return nil
}
if strings.Contains(k, ":") {
parts := strings.Split(k, ":")
if parts[0] == NameAndOrTags {
delete(q.validations, k)
return nil
}
}
}
return ErrValidationNotFound
}
// SetOffset sets Offset of query
func (q *Query) SetOffset(offset int) *Query {
q.Offset = offset
return q
}
// SetLimit sets Offset of query
func (q *Query) SetLimit(limit int) *Query {
q.Limit = limit
return q
}
// Clone makes copy of Query
func (q *Query) Clone() *Query {
qNew := &Query{
Offset: q.Offset,
Limit: q.Limit,
delimiterIN: q.delimiterIN,
delimiterOR: q.delimiterOR,
ignoreUnknown: q.ignoreUnknown,
Error: q.Error,
}
// copy query map
if q.query != nil {
qNew.query = make(map[string][]string)
for key := range q.query {
if len(q.query[key]) > 0 {
qNew.query[key] = make([]string, len(q.query[key]), cap(q.query[key]))
copy(qNew.query[key], q.query[key])
}
}
}
// copy validations
if q.validations != nil {
qNew.validations = make(Validations)
for key := range q.validations {
qNew.validations[key] = q.validations[key]
}
}
// copy Fields
if q.Fields != nil {
qNew.Fields = make([]string, len(q.Fields), cap(q.Fields))
copy(qNew.Fields, q.Fields)
}
// copy Sorts
if q.Sorts != nil {
qNew.Sorts = make([]Sort, len(q.Sorts), cap(q.Sorts))
copy(qNew.Sorts, q.Sorts)
}
// copy Filters
if q.Filters != nil {
qNew.Filters = make([]*Filter, len(q.Filters), cap(q.Filters))
copy(qNew.Filters, q.Filters)
}
return qNew
}
// GetFilter returns filter by name
func (q *Query) GetFilter(name string) (*Filter, error) {
for _, v := range q.Filters {
if v.Name == name {
return v, nil
}
}
return nil, ErrFilterNotFound
}
// Replacer struct for ReplaceNames method
type Replacer map[string]string
// ReplaceNames replace all specified name to new names
// Sometimes we've to hijack properties, for example when we do JOINs,
// so you can ask for filter/field "user_id" but replace it with "users.user_id".
// Parameter is a map[string]string which means map[currentName]newName.
// The library provide beautiful way by using special type rqp.Replacer.
// Example:
// rqp.ReplaceNames(rqp.Replacer{
// "user_id": "users.user_id",
// })
func (q *Query) ReplaceNames(r Replacer) {
for name, newname := range r {
for i, v := range q.Filters {
if v.Name == name {
q.Filters[i].Name = newname
}
}
for i, v := range q.Fields {
if v == name {
q.Fields[i] = newname
}
}
for i, v := range q.Sorts {
if v.By == name {
q.Sorts[i].By = newname
}
}
}
}
// Where returns list of filters for WHERE statement
// return example: `id > 0 AND email LIKE 'some@email.com'`
func (q *Query) Where() string {
if len(q.Filters) == 0 {
return ""
}
var where string
// var OR bool = false
for i := 0; i < len(q.Filters); i++ {
filter := q.Filters[i]
prefix := ""
suffix := ""
if filter.OR == StartOR {
if i == 0 {
prefix = "("
} else {
prefix = " AND ("
}
} else if filter.OR == InOR {
prefix = " OR "
} else if filter.OR == EndOR {
prefix = " OR "
suffix = ")"
} else if i > 0 && len(where) > 0 {
prefix = " AND "
}
if a, err := filter.Where(); err == nil {
where += fmt.Sprintf("%s%s%s", prefix, a, suffix)
} else {
continue
}
}
return where
}
// WHERE returns list of filters for WHERE SQL statement with `WHERE` word
//
// Return example: ` WHERE id > 0 AND email LIKE 'some@email.com'`
//
func (q *Query) WHERE() string {
if len(q.Filters) == 0 {
return ""
}
return " WHERE " + q.Where()
}
// Args returns slice of arguments for WHERE statement
func (q *Query) Args() []interface{} {
args := make([]interface{}, 0)
if len(q.Filters) == 0 {
return args
}
for i := 0; i < len(q.Filters); i++ {
filter := q.Filters[i]
if (filter.Method == IS || filter.Method == NOT) && filter.Value == NULL {
continue
}
if a, err := filter.Args(); err == nil {
args = append(args, a...)
} else {
continue
}
}
return args
}
// SQL returns whole SQL statement
func (q *Query) SQL(table string) string {
return fmt.Sprintf(
"%s FROM %s%s%s%s%s",
q.SELECT(),
table,
q.WHERE(),
q.ORDER(),
q.LIMIT(),
q.OFFSET(),
)
}
// SetUrlQuery change url in the Query for parsing
// uses when you need provide Query from http.HandlerFunc(w http.ResponseWriter, r *http.Request)
// you can do q.SetUrlValues(r.URL.Query())
func (q *Query) SetUrlQuery(query url.Values) *Query {
q.query = query
return q
}
// SetUrlString change url in the Query for parsing
// uses when you would like to provide raw URL string to parsing
func (q *Query) SetUrlString(Url string) error {
u, err := url.Parse(Url)
if err != nil {
return err
}
q.SetUrlQuery(u.Query())
return err
}
// SetValidations change validations rules for the instance
func (q *Query) SetValidations(v Validations) *Query {
q.validations = v
return q
}
// New creates new instance of Query
func New() *Query {
return &Query{
delimiterIN: ",",
delimiterOR: "|",
}
}
// NewQV creates new Query instance with parameters
func NewQV(q url.Values, v Validations) *Query {
query := New().SetUrlQuery(q).SetValidations(v)
return query
}
// NewParse creates new Query instance and Parse it
func NewParse(q url.Values, v Validations) (*Query, error) {
query := New().SetUrlQuery(q).SetValidations(v)
return query, query.Parse()
}
// Parse parses the query of URL
// as query you can use standart http.Request query by r.URL.Query()
func (q *Query) Parse() (err error) {
// clean previously parsed filters
q.cleanFilters()
// construct a slice with required names of filters
requiredNames := q.requiredNames()
for key, values := range q.query {
low := strings.ToLower(key)
switch low {
case "fields", "fields[in]":
low = strings.ReplaceAll(low, "[in]", "")
err = q.parseFields(values, q.validations[low])
delete(requiredNames, low)
case "offset", "offset[in]":
low = strings.ReplaceAll(low, "[in]", "")
err = q.parseOffset(values, q.validations[low])
delete(requiredNames, low)
case "limit", "limit[in]":
low = strings.ReplaceAll(low, "[in]", "")
err = q.parseLimit(values, q.validations[low])
delete(requiredNames, low)
case "sort", "sort[in]":
low = strings.ReplaceAll(low, "[in]", "")
err = q.parseSort(values, q.validations[low])
delete(requiredNames, low)
default:
if len(values) == 0 {
return errors.Wrap(ErrBadFormat, key)
}
for _, value := range values {
err = q.parseFilter(key, value)
if err != nil {
return err
}
}
}
if err != nil {
return errors.Wrap(err, key)
}
}
// check required filters
for requiredName := range requiredNames {
if !q.HaveFilter(requiredName) {
return errors.Wrap(ErrRequired, requiredName)
}
}
return nil
}
// requiredNames returns list of required filters
func (q *Query) requiredNames() map[string]bool {
required := make(map[string]bool)
for name, f := range q.validations {
if strings.Contains(name, ":required") {
oldname := name
// oldname = arg1:required
// oldname = arg2:int:required
newname := strings.Replace(name, ":required", "", 1)
// newname = arg1
// newname = arg2:int
if strings.Contains(newname, ":") {
parts := strings.Split(newname, ":")
name = parts[0]
} else {
name = newname
}
// name = arg1
// name = arg2
low := strings.ToLower(name)
switch low {
case "fields", "fields[in]",
"offset", "offset[in]",
"limit", "limit[in]",
"sort", "sort[in]":
low = strings.ReplaceAll(low, "[in]", "")
required[low] = true
default:
required[name] = true
}
q.validations[newname] = f
delete(q.validations, oldname)
}
}
return required
}
// parseFilter parses one filter
func (q *Query) parseFilter(key, value string) error {
value = strings.TrimSpace(value)
if len(value) == 0 {
return errors.Wrap(ErrEmptyValue, key)
}
if strings.Contains(value, q.delimiterOR) { // OR multiple filter
parts := strings.Split(value, q.delimiterOR)
for i, v := range parts {
if i > 0 {
u := strings.Split(v, "=")
if len(u) < 2 {
return errors.Wrap(ErrBadFormat, key)
}
key = u[0]
v = u[1]
}
v := strings.TrimSpace(v)
if len(v) == 0 {
return errors.Wrap(ErrEmptyValue, key)
}
filter, err := newFilter(key, v, q.delimiterIN, q.validations)
if err != nil {
if err == ErrValidationNotFound {
if q.ignoreUnknown {
continue
} else {
return errors.Wrap(ErrFilterNotFound, key)
}
}
return errors.Wrap(err, key)
}
// set OR
if i == 0 {
filter.OR = StartOR
} else if i == len(parts)-1 {
filter.OR = EndOR
} else {
filter.OR = InOR
}
q.Filters = append(q.Filters, filter)
}
} else { // Single filter
filter, err := newFilter(key, value, q.delimiterIN, q.validations)
if err != nil {
if err == ErrValidationNotFound {
err = ErrFilterNotFound
if q.ignoreUnknown {
return nil
}
}
return errors.Wrap(err, key)
}
q.Filters = append(q.Filters, filter)
}
return nil
}
// clean the filters slice
func (q *Query) cleanFilters() {
if len(q.Filters) > 0 {
for i := range q.Filters {
q.Filters[i] = nil
}
q.Filters = nil
}
}
func (q *Query) parseSort(value []string, validate ValidationFunc) error {
if len(value) != 1 {
return ErrBadFormat
}
if validate == nil {
return ErrValidationNotFound
}
list := value
if strings.Contains(value[0], q.delimiterIN) {
list = strings.Split(value[0], q.delimiterIN)
}
list = cleanSliceString(list)
sort := make([]Sort, 0)
for _, v := range list {
var (
by string
desc bool
)
switch v[0] {
case '-':
by = v[1:]
desc = true
case '+':
by = v[1:]
desc = false
default:
by = v
desc = false
}
if validate != nil {
if err := validate(by); err != nil {
return err
}
}
sort = append(sort, Sort{
By: by,
Desc: desc,
})
}
q.Sorts = sort
return nil
}
func (q *Query) parseFields(value []string, validate ValidationFunc) error {
if len(value) != 1 {
return ErrBadFormat
}
if validate == nil {
return ErrValidationNotFound
}
list := value
if strings.Contains(value[0], q.delimiterIN) {
list = strings.Split(value[0], q.delimiterIN)
}
list = cleanSliceString(list)
if validate != nil {
for _, v := range list {
if err := validate(v); err != nil {
return err
}
}
}
q.Fields = list
return nil
}
func (q *Query) parseOffset(value []string, validate ValidationFunc) error {
if len(value) != 1 {
return ErrBadFormat
}
if len(value[0]) == 0 {
return ErrBadFormat
}
var err error
i, err := strconv.Atoi(value[0])
if err != nil {
return ErrBadFormat
}
if i < 0 {
return errors.Wrapf(ErrNotInScope, "%d", i)
}
if validate != nil {
if err := validate(i); err != nil {
return err
}
}
q.Offset = i
return nil
}
func (q *Query) parseLimit(value []string, validate ValidationFunc) error {
if len(value) != 1 {
return ErrBadFormat
}
if len(value[0]) == 0 {
return ErrBadFormat
}
var err error
i, err := strconv.Atoi(value[0])
if err != nil {
return ErrBadFormat
}
if i <= 0 {
return errors.Wrapf(ErrNotInScope, "%d", i)
}
if validate != nil {
if err := validate(i); err != nil {
return err
}
}
q.Limit = i
return nil
}