-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathqueryparse.go
351 lines (286 loc) · 9.02 KB
/
queryparse.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
package tormenta
import (
"errors"
"fmt"
"net/url"
"reflect"
"strconv"
"strings"
"time"
)
const (
dateFormat1 = "2006-01-02"
// Symbols used in specifying query key:value pairs
// INSIDE a url param e.g. query=myKey:myValue,anotherKey:anotherValue
whereValueSeparator = ":"
whereClauseSeparator = ","
queryStringWhere = "where"
queryStringOr = "or"
queryStringOrderBy = "order"
queryStringOffset = "offset"
queryStringLimit = "limit"
queryStringReverse = "reverse"
queryStringFrom = "from"
queryStringTo = "to"
queryStringMatch = "match"
queryStringStartsWith = "startswith"
queryStringStart = "start"
queryStringEnd = "end"
queryStringIndex = "index"
// Error messages
ErrBadFormatQueryValue = "Bad format for query value"
ErrBadIDFormat = "Bad format for Tormenta ID - %s"
ErrBadLimitFormat = "%s is an invalid input for LIMIT. Expecting a number"
ErrBadOffsetFormat = "%s is an invalid input for OFFSET. Expecting a number"
ErrBadReverseFormat = "%s is an invalid input for REVERSE. Expecting true/false"
ErrBadOrFormat = "%s is an invalid input for OR. Expecting true/false"
ErrBadFromFormat = "Invalid input for FROM. Expecting somthing like '2006-01-02'"
ErrBadToFormat = "Invalid input for TO. Expecting somthing like '2006-01-02'"
ErrFromIsAfterTo = "FROM date is after TO date, making the date range impossible"
ErrIndexWithNoParams = "An index search has been specified, but index search operator has been specified"
ErrTooManyIndexOperatorsSpecified = "An index search can be MATCH, RANGE or STARTSWITH, but not multiple matching operators"
ErrWhereClauseNoIndex = "A WHERE clause requires an index to be specified"
ErrRangeTypeMismatch = "For a range index search, START and END should be of the same type (bool, int, float, string)"
ErrUnmarshall = "Error in format of data to save: %v"
)
func (q *Query) Parse(ignoreLimitOffset bool, s string) error {
// Parse the query string for values
values, err := url.ParseQuery(s)
if err != nil {
return err
}
// Reverse
reverseString := values.Get(queryStringReverse)
if reverseString == "true" {
q.Reverse()
} else if reverseString == "false" || reverseString == "" {
q.UnReverse()
} else {
return fmt.Errorf(ErrBadReverseFormat, reverseString)
}
// Order by
orderByString := values.Get(queryStringOrderBy)
if orderByString != "" {
q.OrderBy(orderByString)
}
// Only apply limit and offset if required
if !ignoreLimitOffset {
limitString := values.Get(queryStringLimit)
if limitString != "" {
n, err := strconv.Atoi(limitString)
if err != nil {
return fmt.Errorf(ErrBadLimitFormat, limitString)
}
q.Limit(n)
}
// Offset
offsetString := values.Get(queryStringOffset)
if offsetString != "" {
n, err := strconv.Atoi(offsetString)
if err != nil {
return fmt.Errorf(ErrBadOffsetFormat, offsetString)
}
q.Offset(n)
}
}
// From / To
fromString := values.Get(queryStringFrom)
toString := values.Get(queryStringTo)
var toValue, fromValue time.Time
if fromString != "" {
fromValue, err = time.Parse(dateFormat1, fromString)
if err != nil {
return errors.New(ErrBadFromFormat)
}
q.From(fromValue)
}
if toString != "" {
toValue, err = time.Parse(dateFormat1, toString)
if err != nil {
return errors.New(ErrBadToFormat)
}
q.To(toValue)
}
// If both from and to where specified, make sure to is later
if fromString != "" && toString != "" && fromValue.After(toValue) {
return errors.New(ErrFromIsAfterTo)
}
// Process each where clause individually
whereClauseStrings := values["where"]
for _, w := range whereClauseStrings {
if err := whereClauseString(w).addToQuery(q); err != nil {
return err
}
}
// And -> Or
orString := values.Get(queryStringOr)
if orString == "true" {
q.Or()
} else if orString == "false" {
q.And() // this is the default anyway
} else if orString == "" {
// Nothing to do here
} else {
return fmt.Errorf(ErrBadOrFormat, orString)
}
return nil
}
type (
whereClauseString string
whereClauseValues map[string]string
)
func (wcs whereClauseString) parse() (whereClauseValues, error) {
whereClauseValues := whereClauseValues{}
components := strings.Split(string(wcs), whereClauseSeparator)
for _, component := range components {
whereKV := strings.Split(component, whereValueSeparator)
if len(whereKV) != 2 {
return whereClauseValues, errors.New(ErrBadFormatQueryValue)
}
whereClauseValues[whereKV[0]] = whereKV[1]
}
return whereClauseValues, nil
}
func (wcs whereClauseString) addToQuery(q *Query) error {
values, err := wcs.parse()
if err != nil {
return err
}
indexString := values.get(queryStringIndex)
if indexString == "" {
return errors.New(ErrWhereClauseNoIndex)
}
return values.addToQuery(q, indexString)
}
func (values whereClauseValues) get(key string) string {
return values[key]
}
func (values whereClauseValues) addToQuery(q *Query, key string) error {
matchString := values.get(queryStringMatch)
startsWithString := values.get(queryStringStartsWith)
startString := values.get(queryStringStart)
endString := values.get(queryStringEnd)
// if no exact match or range or starsWith has been given, return an error
if matchString == "" && startsWithString == "" && (startString == "" && endString == "") {
return errors.New(ErrIndexWithNoParams)
}
// If more than one of MATCH, RANGE and STARTSWITH have been specified
if matchString != "" && (startString != "" || endString != "") ||
matchString != "" && startsWithString != "" ||
startsWithString != "" && (startString != "" || endString != "") {
return errors.New(ErrTooManyIndexOperatorsSpecified)
}
if matchString != "" {
q.Match(key, stringToInterface(matchString))
return nil
}
if startsWithString != "" {
q.StartsWith(key, startsWithString)
return nil
}
// Range
// If both START and END are specified,
// they should be of the same type
if startString != "" && endString != "" {
start := stringToInterface(startString)
end := stringToInterface(endString)
if reflect.TypeOf(start) !=
reflect.TypeOf(end) {
return errors.New(ErrRangeTypeMismatch)
}
q.Range(key, start, end)
return nil
}
// START only
if startString != "" {
q.Range(key, stringToInterface(startString), nil)
return nil
}
// END only
if endString != "" {
q.Range(key, nil, stringToInterface(endString))
return nil
}
return nil
}
func stringToInterface(s string) interface{} {
// Int
i, err := strconv.Atoi(s)
if err == nil {
return i
}
// Float
f, err := strconv.ParseFloat(s, 64)
if err == nil {
return f
}
// Bool
// Bool last, otherwise 0/1 get wrongly interpreted
b, err := strconv.ParseBool(s)
if err == nil {
return b
}
// Default to string
return s
}
// String methods for queries and filters
type queryComponent struct {
key string
value interface{}
}
func (q Query) String() string {
components := []queryComponent{}
if !q.from.IsNil() {
components = append(components, queryComponent{queryStringFrom, q.from.Time().Format(dateFormat1)})
}
if !q.to.IsNil() {
components = append(components, queryComponent{queryStringTo, q.to.Time().Format(dateFormat1)})
}
if q.limit > 0 {
components = append(components, queryComponent{queryStringLimit, q.limit})
}
if q.offset > 0 {
components = append(components, queryComponent{queryStringOffset, q.offset})
}
if len(q.orderByIndexName) > 0 {
components = append(components, queryComponent{queryStringOrderBy, string(q.orderByIndexName)})
}
if q.reverse {
components = append(components, queryComponent{queryStringReverse, q.reverse})
}
if isOr := isOr(q.idsCombinator); isOr {
components = append(components, queryComponent{queryStringOr, isOr})
}
var componentStrings []string
for _, component := range components {
componentStrings = append(componentStrings, fmt.Sprintf("%s=%v", component.key, component.value))
}
for _, filter := range q.filters {
componentStrings = append(componentStrings, fmt.Sprintf("WHERE %s", filter.String()))
}
builtQuery := strings.Join(componentStrings, " | ")
output := []string{string(q.keyRoot)}
if builtQuery != "" {
output = append(output, builtQuery)
}
return strings.Join(output, " | ")
}
func (f filter) String() string {
components := []queryComponent{
{queryStringIndex, string(f.indexName)},
}
if f.start != f.end {
components = append(components, queryComponent{queryStringStart, f.start}, queryComponent{queryStringEnd, f.end})
} else {
if f.isStartsWithQuery {
components = append(components, queryComponent{queryStringStartsWith, f.start})
} else {
components = append(components, queryComponent{queryStringMatch, f.start})
}
}
var componentStrings []string
for _, component := range components {
componentStrings = append(componentStrings, fmt.Sprintf("%s=%v", component.key, component.value))
}
return strings.Join(componentStrings, "; ")
}