-
Notifications
You must be signed in to change notification settings - Fork 28
/
filterbuilder.go
349 lines (296 loc) · 9.81 KB
/
filterbuilder.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
package postgrest
import (
"context"
"encoding/json"
"fmt"
"regexp"
"strconv"
"strings"
)
// FilterBuilder describes a builder for a filtered result set.
type FilterBuilder struct {
client *Client
method string // One of "HEAD", "GET", "POST", "PUT", "DELETE"
body []byte
tableName string
headers map[string]string
params map[string]string
}
// ExecuteString runs the PostgREST query, returning the result as a JSON
// string.
func (f *FilterBuilder) ExecuteString() (string, int64, error) {
return executeString(context.Background(), f.client, f.method, f.body, []string{f.tableName}, f.headers, f.params)
}
// ExecuteStringWithContext runs the PostgREST query, returning the result as
// a JSON string.
func (f *FilterBuilder) ExecuteStringWithContext(ctx context.Context) (string, int64, error) {
return executeString(ctx, f.client, f.method, f.body, []string{f.tableName}, f.headers, f.params)
}
// Execute runs the PostgREST query, returning the result as a byte slice.
func (f *FilterBuilder) Execute() ([]byte, int64, error) {
return execute(context.Background(), f.client, f.method, f.body, []string{f.tableName}, f.headers, f.params)
}
// ExecuteWithContext runs the PostgREST query with the given context,
// returning the result as a byte slice.
func (f *FilterBuilder) ExecuteWithContext(ctx context.Context) ([]byte, int64, error) {
return execute(ctx, f.client, f.method, f.body, []string{f.tableName}, f.headers, f.params)
}
// ExecuteTo runs the PostgREST query, encoding the result to the supplied
// interface. Note that the argument for the to parameter should always be a
// reference to a slice.
func (f *FilterBuilder) ExecuteTo(to interface{}) (countType, error) {
return executeTo(context.Background(), f.client, f.method, f.body, to, []string{f.tableName}, f.headers, f.params)
}
// ExecuteToWithContext runs the PostgREST query with the given context,
// encoding the result to the supplied interface. Note that the argument for
// the to parameter should always be a reference to a slice.
func (f *FilterBuilder) ExecuteToWithContext(ctx context.Context, to interface{}) (countType, error) {
return executeTo(ctx, f.client, f.method, f.body, to, []string{f.tableName}, f.headers, f.params)
}
var filterOperators = []string{"eq", "neq", "gt", "gte", "lt", "lte", "like", "ilike", "is", "in", "cs", "cd", "sl", "sr", "nxl", "nxr", "adj", "ov", "fts", "plfts", "phfts", "wfts"}
func isOperator(value string) bool {
for _, operator := range filterOperators {
if value == operator {
return true
}
}
return false
}
// Filter adds a filtering operator to the query. For a list of available
// operators, see: https://postgrest.org/en/stable/api.html#operators
func (f *FilterBuilder) Filter(column, operator, value string) *FilterBuilder {
if !isOperator(operator) {
f.client.ClientError = fmt.Errorf("invalid filter operator")
return f
}
f.params[column] = fmt.Sprintf("%s.%s", operator, value)
return f
}
func (f *FilterBuilder) And(filters, foreignTable string) *FilterBuilder {
if foreignTable != "" {
f.params[foreignTable+".and"] = fmt.Sprintf("(%s)", filters)
} else {
f.params[foreignTable+"and"] = fmt.Sprintf("(%s)", filters)
}
return f
}
func (f *FilterBuilder) Or(filters, foreignTable string) *FilterBuilder {
if foreignTable != "" {
f.params[foreignTable+".or"] = fmt.Sprintf("(%s)", filters)
} else {
f.params[foreignTable+"or"] = fmt.Sprintf("(%s)", filters)
}
return f
}
func (f *FilterBuilder) Not(column, operator, value string) *FilterBuilder {
if !isOperator(operator) {
return f
}
f.params[column] = fmt.Sprintf("not.%s.%s", operator, value)
return f
}
func (f *FilterBuilder) Match(userQuery map[string]string) *FilterBuilder {
for key, value := range userQuery {
f.params[key] = "eq." + value
}
return f
}
func (f *FilterBuilder) Eq(column, value string) *FilterBuilder {
f.params[column] = "eq." + value
return f
}
func (f *FilterBuilder) Neq(column, value string) *FilterBuilder {
f.params[column] = "neq." + value
return f
}
func (f *FilterBuilder) Gt(column, value string) *FilterBuilder {
f.params[column] = "gt." + value
return f
}
func (f *FilterBuilder) Gte(column, value string) *FilterBuilder {
f.params[column] = "gte." + value
return f
}
func (f *FilterBuilder) Lt(column, value string) *FilterBuilder {
f.params[column] = "lt." + value
return f
}
func (f *FilterBuilder) Lte(column, value string) *FilterBuilder {
f.params[column] = "lte." + value
return f
}
func (f *FilterBuilder) Like(column, value string) *FilterBuilder {
f.params[column] = "like." + value
return f
}
func (f *FilterBuilder) Ilike(column, value string) *FilterBuilder {
f.params[column] = "ilike." + value
return f
}
func (f *FilterBuilder) Is(column, value string) *FilterBuilder {
f.params[column] = "is." + value
return f
}
func (f *FilterBuilder) In(column string, values []string) *FilterBuilder {
var cleanedValues []string
illegalChars := regexp.MustCompile("[,()]")
for _, value := range values {
exp := illegalChars.MatchString(value)
if exp {
cleanedValues = append(cleanedValues, fmt.Sprintf("\"%s\"", value))
} else {
cleanedValues = append(cleanedValues, value)
}
}
f.params[column] = fmt.Sprintf("in.(%s)", strings.Join(cleanedValues, ","))
return f
}
func (f *FilterBuilder) Contains(column string, value []string) *FilterBuilder {
newValue := []string{}
for _, v := range value {
newValue = append(newValue, fmt.Sprintf("%#v", v))
}
valueString := fmt.Sprintf("{%s}", strings.Join(newValue, ","))
f.params[column] = "cs." + valueString
return f
}
func (f *FilterBuilder) ContainedBy(column string, value []string) *FilterBuilder {
newValue := []string{}
for _, v := range value {
newValue = append(newValue, fmt.Sprintf("%#v", v))
}
valueString := fmt.Sprintf("{%s}", strings.Join(newValue, ","))
f.params[column] = "cd." + valueString
return f
}
func (f *FilterBuilder) ContainsObject(column string, value interface{}) *FilterBuilder {
sum, err := json.Marshal(value)
if err != nil {
f.client.ClientError = err
}
f.params[column] = "cs." + string(sum)
return f
}
func (f *FilterBuilder) ContainedByObject(column string, value interface{}) *FilterBuilder {
sum, err := json.Marshal(value)
if err != nil {
f.client.ClientError = err
}
f.params[column] = "cs." + string(sum)
return f
}
func (f *FilterBuilder) RangeLt(column, value string) *FilterBuilder {
f.params[column] = "sl." + value
return f
}
func (f *FilterBuilder) RangeGt(column, value string) *FilterBuilder {
f.params[column] = "sr." + value
return f
}
func (f *FilterBuilder) RangeGte(column, value string) *FilterBuilder {
f.params[column] = "nxl." + value
return f
}
func (f *FilterBuilder) RangeLte(column, value string) *FilterBuilder {
f.params[column] = "nxr." + value
return f
}
func (f *FilterBuilder) RangeAdjacent(column, value string) *FilterBuilder {
f.params[column] = "adj." + value
return f
}
func (f *FilterBuilder) Overlaps(column string, value []string) *FilterBuilder {
newValue := []string{}
for _, v := range value {
newValue = append(newValue, fmt.Sprintf("%#v", v))
}
valueString := fmt.Sprintf("{%s}", strings.Join(newValue, ","))
f.params[column] = "ov." + valueString
return f
}
// TextSearch performs a full-text search filter. For more information, see
// https://postgrest.org/en/stable/api.html#fts.
func (f *FilterBuilder) TextSearch(column, userQuery, config, tsType string) *FilterBuilder {
var typePart, configPart string
if tsType == "plain" {
typePart = "pl"
} else if tsType == "phrase" {
typePart = "ph"
} else if tsType == "websearch" {
typePart = "w"
} else if tsType == "" {
typePart = ""
} else {
f.client.ClientError = fmt.Errorf("invalid text search type")
return f
}
if config != "" {
configPart = fmt.Sprintf("(%s)", config)
}
f.params[column] = typePart + "fts" + configPart + "." + userQuery
return f
}
// OrderOpts describes the options to be provided to Order.
type OrderOpts struct {
Ascending bool
NullsFirst bool
ForeignTable string
}
// DefaultOrderOpts is the default set of options used by Order.
var DefaultOrderOpts = OrderOpts{
Ascending: false,
NullsFirst: false,
ForeignTable: "",
}
// Limit the result to the specified count.
func (f *FilterBuilder) Limit(count int, foreignTable string) *FilterBuilder {
if foreignTable != "" {
f.params[foreignTable+".limit"] = strconv.Itoa(count)
} else {
f.params["limit"] = strconv.Itoa(count)
}
return f
}
// Order the result with the specified column. A pointer to an OrderOpts
// object can be supplied to specify ordering options.
func (f *FilterBuilder) Order(column string, opts *OrderOpts) *FilterBuilder {
if opts == nil {
opts = &DefaultOrderOpts
}
key := "order"
if opts.ForeignTable != "" {
key = opts.ForeignTable + ".order"
}
ascendingString := "desc"
if opts.Ascending {
ascendingString = "asc"
}
nullsString := "nullslast"
if opts.NullsFirst {
nullsString = "nullsfirst"
}
existingOrder, ok := f.params[key]
if ok && existingOrder != "" {
f.params[key] = fmt.Sprintf("%s,%s.%s.%s", existingOrder, column, ascendingString, nullsString)
} else {
f.params[key] = fmt.Sprintf("%s.%s.%s", column, ascendingString, nullsString)
}
return f
}
// Range Limits the result to rows within the specified range, inclusive.
func (f *FilterBuilder) Range(from, to int, foreignTable string) *FilterBuilder {
if foreignTable != "" {
f.params[foreignTable+".offset"] = strconv.Itoa(from)
f.params[foreignTable+".limit"] = strconv.Itoa(to - from + 1)
} else {
f.params["offset"] = strconv.Itoa(from)
f.params["limit"] = strconv.Itoa(to - from + 1)
}
return f
}
// Single Retrieves only one row from the result. The total result set must be one row
// (e.g., by using Limit). Otherwise, this will result in an error.
func (f *FilterBuilder) Single() *FilterBuilder {
f.headers["Accept"] = "application/vnd.pgrst.object+json"
return f
}