forked from rs/rest-layer
/
query.go
358 lines (326 loc) · 9.7 KB
/
query.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
package schema
import (
"encoding/json"
"errors"
"fmt"
"reflect"
)
// Query defines an expression against a schema to perform a match on schema's data.
type Query []Expression
// Expression is a query or query component that can be matched against a payoad.
type Expression interface {
Match(payload map[string]interface{}) bool
}
// Value represents any kind of value to use in query
type Value interface{}
// And joins query clauses with a logical AND, returns all documents
// that match the conditions of both clauses.
type And []Expression
// Or joins query clauses with a logical OR, returns all documents that
// match the conditions of either clause.
type Or []Expression
// In natches any of the values specified in an array.
type In struct {
Field string
Values []Value
}
// NotIn matches none of the values specified in an array.
type NotIn struct {
Field string
Values []Value
}
// Equal matches all values that are equal to a specified value.
type Equal struct {
Field string
Value Value
}
// NotEqual matches all values that are not equal to a specified value.
type NotEqual struct {
Field string
Value Value
}
// Exist matches all values which are present, even if nil
type Exist struct {
Field string
}
// NotExist matches all values which are absent
type NotExist struct {
Field string
}
// GreaterThan matches values that are greater than a specified value.
type GreaterThan struct {
Field string
Value float64
}
// GreaterOrEqual matches values that are greater than or equal to a specified value.
type GreaterOrEqual struct {
Field string
Value float64
}
// LowerThan matches values that are less than a specified value.
type LowerThan struct {
Field string
Value float64
}
// LowerOrEqual matches values that are less than or equal to a specified value.
type LowerOrEqual struct {
Field string
Value float64
}
// NewQuery returns a new query with the provided key/value validated against validator
func NewQuery(q map[string]interface{}, validator Validator) (Query, error) {
return validateQuery(q, validator, "")
}
// ParseQuery parses and validate a query as string
func ParseQuery(query string, validator Validator) (Query, error) {
var j interface{}
if err := json.Unmarshal([]byte(query), &j); err != nil {
return nil, errors.New("must be valid JSON")
}
q, ok := j.(map[string]interface{})
if !ok {
return nil, errors.New("must be a JSON object")
}
return validateQuery(q, validator, "")
}
// validateQuery recursively validates and cast a query
func validateQuery(q map[string]interface{}, validator Validator, parentKey string) (Query, error) {
queries := Query{}
for key, exp := range q {
switch key {
case "$exists":
if parentKey == "" {
return nil, errors.New("$exists can't be at first level")
}
positive, ok := exp.(bool)
if !ok {
return nil, errors.New("$exists can only get Boolean as value")
}
if positive {
queries = append(queries, Exist{Field: parentKey})
} else {
queries = append(queries, NotExist{Field: parentKey})
}
case "$ne":
op := key
if parentKey == "" {
return nil, fmt.Errorf("%s can't be at first level", op)
}
if field := validator.GetField(parentKey); field != nil {
if field.Validator != nil {
if _, err := field.Validator.Validate(exp); err != nil {
return nil, fmt.Errorf("invalid query expression for field `%s': %s", parentKey, err)
}
}
}
queries = append(queries, NotEqual{Field: parentKey, Value: exp})
case "$gt", "$gte", "$lt", "$lte":
op := key
if parentKey == "" {
return nil, fmt.Errorf("%s can't be at first level", op)
}
n, ok := isNumber(exp)
if !ok {
return nil, fmt.Errorf("%s: value for %s must be a number", parentKey, op)
}
if field := validator.GetField(parentKey); field != nil {
if field.Validator != nil {
switch field.Validator.(type) {
case Integer, Float:
if _, err := field.Validator.Validate(exp); err != nil {
return nil, fmt.Errorf("invalid query expression for field `%s': %s", parentKey, err)
}
default:
return nil, fmt.Errorf("%s: cannot apply %s operation on a non numerical field", parentKey, op)
}
}
}
switch op {
case "$gt":
queries = append(queries, GreaterThan{Field: parentKey, Value: n})
case "$gte":
queries = append(queries, GreaterOrEqual{Field: parentKey, Value: n})
case "$lt":
queries = append(queries, LowerThan{Field: parentKey, Value: n})
case "$lte":
queries = append(queries, LowerOrEqual{Field: parentKey, Value: n})
}
case "$in", "$nin":
op := key
if parentKey == "" {
return nil, fmt.Errorf("%s can't be at first level", op)
}
if _, ok := exp.(map[string]interface{}); ok {
return nil, fmt.Errorf("%s: value for %s can't be a dict", parentKey, op)
}
values := []Value{}
if field := validator.GetField(parentKey); field != nil {
vals, ok := exp.([]interface{})
if !ok {
vals = []interface{}{exp}
}
if field.Validator != nil {
for _, v := range vals {
if _, err := field.Validator.Validate(v); err != nil {
return nil, fmt.Errorf("invalid query expression (%s) for field `%s': %s", v, parentKey, err)
}
}
}
for _, v := range vals {
values = append(values, v)
}
}
switch op {
case "$in":
queries = append(queries, In{Field: parentKey, Values: values})
case "$nin":
queries = append(queries, NotIn{Field: parentKey, Values: values})
}
case "$or", "$and":
op := key
var subQueries []interface{}
var ok bool
if subQueries, ok = exp.([]interface{}); !ok {
return nil, fmt.Errorf("value for %s must be an array of dicts", op)
}
if len(subQueries) < 2 {
return nil, fmt.Errorf("%s must contain at least to elements", op)
}
// Cast map to Query object
castedExp := []Expression{}
for _, subQuery := range subQueries {
sq, ok := subQuery.(map[string]interface{})
if !ok {
return nil, fmt.Errorf("value for %s must be an array of dicts", op)
}
query, err := validateQuery(sq, validator, "")
if err != nil {
return nil, err
}
castedExp = append(castedExp, query...)
}
switch op {
case "$or":
queries = append(queries, Or(castedExp))
case "$and":
queries = append(queries, And(castedExp))
}
default:
// Field query
field := validator.GetField(key)
if field == nil {
return nil, fmt.Errorf("unknown query field: %s", key)
}
if !field.Filterable {
return nil, fmt.Errorf("field is not filterable: %s", key)
}
if parentKey != "" {
return nil, fmt.Errorf("%s: invalid expression", parentKey)
}
if subQuery, ok := exp.(map[string]interface{}); ok {
sq, err := validateQuery(subQuery, validator, key)
if err != nil {
return nil, err
}
queries = append(queries, sq...)
} else {
// Exact match
if field.Validator != nil {
if _, err := field.Validator.Validate(exp); err != nil {
return nil, fmt.Errorf("invalid query expression for field `%s': %s", key, err)
}
}
queries = append(queries, Equal{Field: key, Value: exp})
}
}
}
return queries, nil
}
// Match implements Expression interface
func (e Query) Match(payload map[string]interface{}) bool {
// Run each sub queries like a root query, stop/pass on first match
for _, subQuery := range e {
if !subQuery.Match(payload) {
return false
}
}
return true
}
// Match implements Expression interface
func (e And) Match(payload map[string]interface{}) bool {
// Run each sub queries like a root query, stop/pass on first match
for _, subQuery := range e {
if !subQuery.Match(payload) {
return false
}
}
return true
}
// Match implements Expression interface
func (e Or) Match(payload map[string]interface{}) bool {
// Run each sub queries like a root query, stop/pass on first match
for _, subQuery := range e {
if subQuery.Match(payload) {
return true
}
}
return false
}
// Match implements Expression interface
func (e In) Match(payload map[string]interface{}) bool {
value := getField(payload, e.Field)
for _, v := range e.Values {
if reflect.DeepEqual(v, value) {
return true
}
}
return false
}
// Match implements Expression interface
func (e NotIn) Match(payload map[string]interface{}) bool {
value := getField(payload, e.Field)
for _, v := range e.Values {
if reflect.DeepEqual(v, value) {
return false
}
}
return true
}
// Match implements Expression interface
func (e Equal) Match(payload map[string]interface{}) bool {
return reflect.DeepEqual(getField(payload, e.Field), e.Value)
}
// Match implements Expression interface
func (e NotEqual) Match(payload map[string]interface{}) bool {
return !reflect.DeepEqual(getField(payload, e.Field), e.Value)
}
// Match implements Expression interface
func (e Exist) Match(payload map[string]interface{}) bool {
_, found := getFieldExist(payload, e.Field)
return found
}
// Match implements Expression interface
func (e NotExist) Match(payload map[string]interface{}) bool {
_, found := getFieldExist(payload, e.Field)
return !found
}
// Match implements Expression interface
func (e GreaterThan) Match(payload map[string]interface{}) bool {
n, ok := isNumber(getField(payload, e.Field))
return ok && (n > e.Value)
}
// Match implements Expression interface
func (e GreaterOrEqual) Match(payload map[string]interface{}) bool {
n, ok := isNumber(getField(payload, e.Field))
return ok && (n >= e.Value)
}
// Match implements Expression interface
func (e LowerThan) Match(payload map[string]interface{}) bool {
n, ok := isNumber(getField(payload, e.Field))
return ok && (n < e.Value)
}
// Match implements Expression interface
func (e LowerOrEqual) Match(payload map[string]interface{}) bool {
n, ok := isNumber(getField(payload, e.Field))
return ok && (n <= e.Value)
}