-
Notifications
You must be signed in to change notification settings - Fork 0
/
query-filters.go
executable file
·90 lines (69 loc) · 2.32 KB
/
query-filters.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
package gen
import (
"context"
"fmt"
"strings"
"github.com/jinzhu/gorm"
"github.com/vektah/gqlparser/ast"
)
type FileQueryFilter struct {
Query *string
}
func (qf *FileQueryFilter) Apply(ctx context.Context, dialect gorm.Dialect, selectionSet *ast.SelectionSet, wheres *[]string, values *[]interface{}, joins *[]string) error {
if qf.Query == nil {
return nil
}
fields := []*ast.Field{}
if selectionSet != nil {
for _, s := range *selectionSet {
if f, ok := s.(*ast.Field); ok {
fields = append(fields, f)
}
}
} else {
return fmt.Errorf("Cannot query with 'q' attribute without items field.")
}
queryParts := strings.Split(*qf.Query, " ")
for _, part := range queryParts {
ors := []string{}
if err := qf.applyQueryWithFields(dialect, fields, part, TableName("files"), &ors, values, joins); err != nil {
return err
}
*wheres = append(*wheres, "("+strings.Join(ors, " OR ")+")")
}
return nil
}
func (qf *FileQueryFilter) applyQueryWithFields(dialect gorm.Dialect, fields []*ast.Field, query, alias string, ors *[]string, values *[]interface{}, joins *[]string) error {
if len(fields) == 0 {
return nil
}
fieldsMap := map[string][]*ast.Field{}
for _, f := range fields {
fieldsMap[f.Name] = append(fieldsMap[f.Name], f)
}
if _, ok := fieldsMap["name"]; ok {
column := dialect.Quote(alias) + "." + dialect.Quote("name")
*ors = append(*ors, fmt.Sprintf("%[1]s LIKE ? OR %[1]s LIKE ?", column))
*values = append(*values, query+"%", "% "+query+"%")
}
if _, ok := fieldsMap["size"]; ok {
cast := "TEXT"
if dialect.GetName() == "mysql" {
cast = "CHAR"
}
column := fmt.Sprintf("CAST(%s"+dialect.Quote("size")+" AS %s)", dialect.Quote(alias)+".", cast)
*ors = append(*ors, fmt.Sprintf("%[1]s LIKE ? OR %[1]s LIKE ?", column))
*values = append(*values, query+"%", "% "+query+"%")
}
if _, ok := fieldsMap["contentType"]; ok {
column := dialect.Quote(alias) + "." + dialect.Quote("contentType")
*ors = append(*ors, fmt.Sprintf("%[1]s LIKE ? OR %[1]s LIKE ?", column))
*values = append(*values, query+"%", "% "+query+"%")
}
if _, ok := fieldsMap["reference"]; ok {
column := dialect.Quote(alias) + "." + dialect.Quote("reference")
*ors = append(*ors, fmt.Sprintf("%[1]s LIKE ? OR %[1]s LIKE ?", column))
*values = append(*values, query+"%", "% "+query+"%")
}
return nil
}