forked from rethinkdb/rethinkdb-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathquery.go
179 lines (163 loc) · 4.65 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
package gorethink
import (
"code.google.com/p/goprotobuf/proto"
"fmt"
p "github.com/dancannon/gorethink/ql2"
"strconv"
"strings"
)
type termsList []RqlTerm
type termsObj map[string]RqlTerm
type RqlTerm struct {
name string
termType p.Term_TermType
data interface{}
args []RqlTerm
optArgs map[string]RqlTerm
}
// build takes the query tree and turns it into a protobuf term tree.
func (t RqlTerm) build() *p.Term {
switch t.termType {
case p.Term_DATUM:
datum, err := constructDatum(t)
if err != nil {
panic(err)
}
return datum
default:
args := []*p.Term{}
optArgs := []*p.Term_AssocPair{}
term := &p.Term{
Type: t.termType.Enum(),
}
for _, v := range t.args {
args = append(args, v.build())
}
for k, v := range t.optArgs {
optArgs = append(optArgs, &p.Term_AssocPair{
Key: proto.String(k),
Val: v.build(),
})
}
term.Args = args
term.Optargs = optArgs
return term
}
}
// compose returns a string representation of the query tree
func (t RqlTerm) String() string {
switch t.termType {
case p.Term_MAKE_ARRAY:
return fmt.Sprintf("[%s]", strings.Join(argsToStringSlice(t.args), ", "))
case p.Term_MAKE_OBJ:
return fmt.Sprintf("{%s}", strings.Join(optArgsToStringSlice(t.optArgs), ", "))
case p.Term_FUNC:
// Get string representation of each argument
args := []string{}
for _, v := range t.args[0].args {
args = append(args, fmt.Sprintf("var_%d", v.data))
}
return fmt.Sprintf("func(%s r.RqlTerm) r.RqlTerm { return %s }",
strings.Join(args, ", "),
t.args[1].String(),
)
case p.Term_VAR:
return fmt.Sprintf("var_%s", t.args[0])
case p.Term_IMPLICIT_VAR:
return "r.Row"
case p.Term_DATUM:
switch v := t.data.(type) {
case string:
return strconv.Quote(v)
default:
return fmt.Sprintf("%v", v)
}
default:
if t.name != "" {
return fmt.Sprintf("r.%s(%s)", t.name, strings.Join(allArgsToStringSlice(t.args, t.optArgs), ", "))
} else {
return fmt.Sprintf("(%s)", strings.Join(allArgsToStringSlice(t.args, t.optArgs), ", "))
}
}
}
type WriteResponse struct {
Errors int
Created int
Inserted int
Updated int
Unchanged int
Replaced int
Deleted int
GeneratedKeys []string `gorethink:"generated_keys"`
FirstError string `gorethink:"first_error"` // populated if Errors > 0
NewValue interface{} `gorethink:"new_val"`
OldValue interface{} `gorethink:"old_val"`
}
// Run runs a query using the given connection.
//
// Optional arguments :
// "db", "use_outdated" (defaults to false), "noreply" (defaults to false) and "time_format".
//
// rows, err := query.Run(sess)
// if err != nil {
// // error
// }
// for rows.Next() {
// doc := MyDocumentType{}
// err := r.Scan(&doc)
// // Do something with row
// }
func (t RqlTerm) Run(s *Session, args ...interface{}) (*ResultRows, error) {
argm := optArgsToMap([]string{"db", "use_outdated", "noreply", "time_format"}, args)
return s.startQuery(t, argm)
}
// Run runs a query using the given connection but unlike Run returns ResultRow.
// This function should be used if your query only returns a single row.
//
// Optional arguments :
// "db", "use_outdated" (defaults to false), "noreply" (defaults to false) and "time_format".
//
// row, err := query.RunRow(sess, "use_outdated", true)
// if err != nil {
// // error
// }
// if row.IsNil() {
// // nothing was found
// }
// err = row.Scan(&doc)
func (t RqlTerm) RunRow(s *Session, args ...interface{}) (*ResultRow, error) {
rows, err := t.Run(s, args...)
if err == nil {
defer rows.Close()
rows.Next()
}
return &ResultRow{rows: rows, err: err}, err
}
// RunWrite runs a query using the given connection but unlike Run automatically
// scans the result into a variable of type WriteResponse. This function should be used
// if you are running a write query (such as Insert, Update, TableCreate, etc...)
//
// Optional arguments :
// "db", "use_outdated" (defaults to false), "noreply" (defaults to false) and "time_format".
//
// res, err := r.Db("database").Table("table").Insert(doc).RunWrite(sess, "noreply", true)
func (t RqlTerm) RunWrite(s *Session, args ...interface{}) (WriteResponse, error) {
var response WriteResponse
row, err := t.RunRow(s, args...)
if err == nil {
err = row.Scan(&response)
}
return response, err
}
// Exec runs the query but does not return the result (It also automatically sets
// the noreply option).
//
// Optional arguments :
// "db", "use_outdated" (defaults to false) and "time_format".
func (t RqlTerm) Exec(s *Session, args ...interface{}) error {
// Ensure that noreply is set to true
args = append(args, "noreply")
args = append(args, true)
_, err := t.Run(s, args...)
return err
}