-
Notifications
You must be signed in to change notification settings - Fork 4
/
query_gorm.go
194 lines (155 loc) · 3.98 KB
/
query_gorm.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
// Define data structure for a query request
// {
// "where":[{"key": "name", "op": "=", "val": "Thomas"}],
// "order": [{"key": "name", "val": "asc"}]
// "limit": 1
// }
package goal
import (
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"reflect"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
)
var ops map[string]bool
func allowedOps() map[string]bool {
if ops == nil {
ops = map[string]bool{
"=": true,
">": true,
">=": true,
"<": true,
"<=": true,
"<>": true,
"in": true,
"like": true,
}
}
return ops
}
// QueryItem defines most basic element of a query.
// For example: name = Thomas
type QueryItem struct {
Key string `json:"key"`
Op string `json:"op"`
Val interface{} `json:"val"`
Or []*QueryItem `json:"or"`
}
func (item *QueryItem) getQuery(scope *gorm.Scope) (string, error) {
_, exists := allowedOps()[item.Op]
if !exists {
str := fmt.Sprintf("Invalid SQL operator: %s", item.Op)
return "", errors.New(str)
}
if !scope.HasColumn(item.Key) {
str := fmt.Sprintf("Column does not exist: %s", item.Key)
return "", errors.New(str)
}
var query string
if item.Op == "in" {
query = fmt.Sprintf("%s %s (?)", item.Key, item.Op)
} else {
query = fmt.Sprintf("%s %s ?", item.Key, item.Op)
}
return query, nil
}
// QueryParams defines structure of a query. Where clause
// may include multiple QueryItem and connect by "AND" operator
type QueryParams struct {
Where []*QueryItem `json:"where"`
Limit int64 `json:"limit"`
Order map[string]bool `json:"order"`
Include []string `json:"include"`
}
// Find constructs the query, return error immediately if query is invalid,
// and query database if everything is valid
func (params *QueryParams) Find(resource interface{}, results interface{}) error {
scope := db.NewScope(resource)
qryDB := db.New()
// Parse where clause
if params.Where != nil {
for _, item := range params.Where {
query, err := item.getQuery(scope)
// Return immediately if query is invalid
if err != nil {
return err
}
qryDB = qryDB.Where(query, item.Val)
if item.Or != nil {
for _, orItem := range item.Or {
query, err = orItem.getQuery(scope)
// Return immediately if query is invalid
if err != nil {
return err
}
qryDB = qryDB.Or(query, orItem.Val)
}
}
}
}
if params.Limit != 0 {
qryDB = qryDB.Limit(params.Limit)
}
if params.Order != nil {
for name, order := range params.Order {
if !scope.HasColumn(name) {
errorMsg := fmt.Sprintf("Column %s does not exist", name)
return errors.New(errorMsg)
}
qryDB = qryDB.Order(name, order)
}
}
if params.Include != nil {
for _, name := range params.Include {
qryDB = qryDB.Preload(name)
}
}
// Query the database
qryDB.Find(results)
return nil
}
// HandleQuery retrieves results filtered by request parameters
func HandleQuery(rType reflect.Type, request *http.Request) (int, interface{}, error) {
if db == nil {
panic("Database is not initialized yet")
}
vars := mux.Vars(request)
// Retrieve query parameter
query, err := url.QueryUnescape(vars["query"])
if err != nil {
return 500, nil, err
}
var params QueryParams
err = json.Unmarshal([]byte(query), ¶ms)
if err != nil {
fmt.Println(err)
return 500, nil, err
}
resource := newObjectWithType(rType)
results := dynamicSlice(resource)
err = params.Find(resource, results)
if err != nil {
return 500, nil, err
}
// Check permission for each item, remove item which doesn't have permission
var filtered []interface{}
switch reflect.TypeOf(results).Elem().Kind() {
case reflect.Slice:
s := reflect.ValueOf(results).Elem()
for i := 0; i < s.Len(); i++ {
item := s.Index(i).Interface()
err = CanPerform(item, request, true)
// Only add to the filtered slice if no permission error
if err == nil {
filtered = append(filtered, item)
}
}
default:
panic("results should be a slice")
}
return 200, filtered, nil
}