/
query_control.go
285 lines (243 loc) · 8.14 KB
/
query_control.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
package gorethink
import (
"bytes"
"encoding/base64"
"fmt"
"io"
"io/ioutil"
"reflect"
"time"
p "github.com/dancannon/gorethink/ql2"
)
var byteSliceType = reflect.TypeOf([]byte(nil))
// Expr converts any value to an expression. Internally it uses the `json`
// module to convert any literals, so any type annotations or methods understood
// by that module can be used. If the value cannot be converted, an error is
// returned at query .Run(session) time.
//
// If you want to call expression methods on an object that is not yet an
// expression, this is the function you want.
func Expr(value interface{}) Term {
return expr(value, 20)
}
func expr(value interface{}, depth int) Term {
if depth <= 0 {
panic("Maximum nesting depth limit exceeded")
}
if value == nil {
return Term{
termType: p.Term_DATUM,
data: nil,
}
}
switch val := value.(type) {
case Term:
return val
case time.Time:
return EpochTime(val.Unix())
case io.Reader:
b, err := ioutil.ReadAll(val)
if err != nil {
panic(fmt.Sprintf("Error reading bytes from reader: %s", err.Error()))
}
return Binary(b)
case bytes.Buffer:
return Binary(val)
case []byte:
return Binary(val)
case []interface{}:
vals := []Term{}
for _, v := range val {
vals = append(vals, expr(v, depth))
}
return makeArray(vals)
case map[string]interface{}:
vals := map[string]Term{}
for k, v := range val {
vals[k] = expr(v, depth)
}
return makeObject(vals)
default:
// Use reflection to check for other types
typ := reflect.TypeOf(val)
rval := reflect.ValueOf(val)
if typ.Kind() == reflect.Ptr || typ.Kind() == reflect.Interface {
v := reflect.ValueOf(val)
if v.IsNil() {
return Term{
termType: p.Term_DATUM,
data: nil,
}
}
val = v.Elem().Interface()
typ = reflect.TypeOf(val)
}
if typ.Kind() == reflect.Func {
return makeFunc(val)
}
if typ.Kind() == reflect.Struct {
data, err := encode(val)
if err != nil || data == nil {
return Term{
termType: p.Term_DATUM,
data: nil,
}
}
return expr(data, depth-1)
}
if typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array {
// Check if slice is a byte slice
if typ.Elem().Kind() == reflect.Uint8 {
return Binary(rval.Bytes())
} else {
vals := []Term{}
for i := 0; i < rval.Len(); i++ {
vals = append(vals, expr(rval.Index(i).Interface(), depth))
}
return makeArray(vals)
}
}
if typ.Kind() == reflect.Map {
vals := map[string]Term{}
for _, k := range rval.MapKeys() {
vals[k.String()] = expr(rval.MapIndex(k).Interface(), depth)
}
return makeObject(vals)
}
// If no other match was found then return a datum value
return Term{
termType: p.Term_DATUM,
data: val,
}
}
}
// Create a JavaScript expression.
func Js(jssrc interface{}) Term {
return constructRootTerm("Js", p.Term_JAVASCRIPT, []interface{}{jssrc}, map[string]interface{}{})
}
type HttpOpts struct {
// General Options
Timeout interface{} `gorethink:"timeout,omitempty"`
Reattempts interface{} `gorethink:"reattempts,omitempty"`
Redirects interface{} `gorethink:"redirect,omitempty"`
Verify interface{} `gorethink:"verify,omitempty"`
ResultFormat interface{} `gorethink:"resul_format,omitempty"`
// Request Options
Method interface{} `gorethink:"method,omitempty"`
Auth interface{} `gorethink:"auth,omitempty"`
Params interface{} `gorethink:"params,omitempty"`
Header interface{} `gorethink:"header,omitempty"`
Data interface{} `gorethink:"data,omitempty"`
// Pagination
Page interface{} `gorethink:"page,omitempty"`
PageLimit interface{} `gorethink:"page_limit,omitempty"`
}
func (o *HttpOpts) toMap() map[string]interface{} {
return optArgsToMap(o)
}
// Parse a JSON string on the server.
func Http(url interface{}, optArgs ...HttpOpts) Term {
opts := map[string]interface{}{}
if len(optArgs) >= 1 {
opts = optArgs[0].toMap()
}
return constructRootTerm("Http", p.Term_HTTP, []interface{}{url}, opts)
}
// Parse a JSON string on the server.
func Json(args ...interface{}) Term {
return constructRootTerm("Json", p.Term_JSON, args, map[string]interface{}{})
}
// Throw a runtime error. If called with no arguments inside the second argument
// to `default`, re-throw the current error.
func Error(args ...interface{}) Term {
return constructRootTerm("Error", p.Term_ERROR, args, map[string]interface{}{})
}
// Args is a special term usd to splice an array of arguments into another term.
// This is useful when you want to call a varadic term such as GetAll with a set
// of arguments provided at runtime.
func Args(args ...interface{}) Term {
return constructRootTerm("Args", p.Term_ARGS, args, map[string]interface{}{})
}
// Binary encapsulates binary data within a query.
func Binary(data interface{}) Term {
var b []byte
switch data := data.(type) {
case Term:
return constructRootTerm("Binary", p.Term_BINARY, []interface{}{data}, map[string]interface{}{})
case io.Reader:
var err error
b, err = ioutil.ReadAll(data)
if err != nil {
panic(fmt.Sprintf("Error reading bytes from reader: %s", err.Error()))
}
return Binary(b)
case bytes.Buffer:
b = data.Bytes()
case []byte:
b = data
default:
typ := reflect.TypeOf(data)
if (typ.Kind() == reflect.Slice || typ.Kind() == reflect.Array) &&
typ.Elem().Kind() == reflect.Uint8 {
return Binary(reflect.ValueOf(data).Bytes())
}
panic("Unsupported binary type")
}
return binaryTerm(base64.StdEncoding.EncodeToString(b))
}
func binaryTerm(data string) Term {
t := constructRootTerm("Binary", p.Term_BINARY, []interface{}{}, map[string]interface{}{})
t.data = data
return t
}
// Evaluate the expr in the context of one or more value bindings. The type of
// the result is the type of the value returned from expr.
func (t Term) Do(args ...interface{}) Term {
newArgs := []interface{}{}
newArgs = append(newArgs, funcWrap(args[len(args)-1]))
newArgs = append(newArgs, t)
newArgs = append(newArgs, args[:len(args)-1]...)
return constructRootTerm("Do", p.Term_FUNCALL, newArgs, map[string]interface{}{})
}
// Evaluate the expr in the context of one or more value bindings. The type of
// the result is the type of the value returned from expr.
func Do(args ...interface{}) Term {
newArgs := []interface{}{}
newArgs = append(newArgs, funcWrap(args[len(args)-1]))
newArgs = append(newArgs, args[:len(args)-1]...)
return constructRootTerm("Do", p.Term_FUNCALL, newArgs, map[string]interface{}{})
}
// Evaluate one of two control paths based on the value of an expression.
// branch is effectively an if renamed due to language constraints.
//
// The type of the result is determined by the type of the branch that gets executed.
func Branch(args ...interface{}) Term {
return constructRootTerm("Branch", p.Term_BRANCH, args, map[string]interface{}{})
}
// Loop over a sequence, evaluating the given write query for each element.
func (t Term) ForEach(args ...interface{}) Term {
return constructMethodTerm(t, "Foreach", p.Term_FOREACH, funcWrapArgs(args), map[string]interface{}{})
}
// Handle non-existence errors. Tries to evaluate and return its first argument.
// If an error related to the absence of a value is thrown in the process, or if
// its first argument returns null, returns its second argument. (Alternatively,
// the second argument may be a function which will be called with either the
// text of the non-existence error or null.)
func (t Term) Default(args ...interface{}) Term {
return constructMethodTerm(t, "Default", p.Term_DEFAULT, args, map[string]interface{}{})
}
// Converts a value of one type into another.
//
// You can convert: a selection, sequence, or object into an ARRAY, an array of
// pairs into an OBJECT, and any DATUM into a STRING.
func (t Term) CoerceTo(args ...interface{}) Term {
return constructMethodTerm(t, "CoerceTo", p.Term_COERCE_TO, args, map[string]interface{}{})
}
// Gets the type of a value.
func (t Term) TypeOf(args ...interface{}) Term {
return constructMethodTerm(t, "TypeOf", p.Term_TYPEOF, args, map[string]interface{}{})
}
// Get information about a RQL value.
func (t Term) Info(args ...interface{}) Term {
return constructMethodTerm(t, "Info", p.Term_INFO, args, map[string]interface{}{})
}