-
Notifications
You must be signed in to change notification settings - Fork 104
/
bucket_viewquery.go
278 lines (227 loc) · 6.7 KB
/
bucket_viewquery.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
package gocb
import (
"encoding/json"
"net/url"
"strings"
"time"
gocbcore "github.com/couchbase/gocbcore/v9"
"github.com/pkg/errors"
)
type jsonViewResponse struct {
TotalRows uint64 `json:"total_rows,omitempty"`
DebugInfo interface{} `json:"debug_info,omitempty"`
}
type jsonViewRow struct {
ID string `json:"id"`
Key json.RawMessage `json:"key"`
Value json.RawMessage `json:"value"`
}
// ViewMetaData provides access to the meta-data properties of a view query result.
type ViewMetaData struct {
TotalRows uint64
Debug interface{}
}
func (meta *ViewMetaData) fromData(data jsonViewResponse) error {
meta.TotalRows = data.TotalRows
meta.Debug = data.DebugInfo
return nil
}
// ViewRow represents a single row returned from a view query.
type ViewRow struct {
ID string
keyBytes []byte
valueBytes []byte
}
// Key returns the key associated with this view row.
func (vr *ViewRow) Key(valuePtr interface{}) error {
return json.Unmarshal(vr.keyBytes, valuePtr)
}
// Value returns the value associated with this view row.
func (vr *ViewRow) Value(valuePtr interface{}) error {
return json.Unmarshal(vr.valueBytes, valuePtr)
}
type viewRowReader interface {
NextRow() []byte
Err() error
MetaData() ([]byte, error)
Close() error
}
// ViewResultRaw provides raw access to views data.
// VOLATILE: This API is subject to change at any time.
type ViewResultRaw struct {
reader viewRowReader
}
// NextBytes returns the next row as bytes.
func (vrr *ViewResultRaw) NextBytes() []byte {
return vrr.reader.NextRow()
}
// Err returns any errors that have occurred on the stream
func (vrr *ViewResultRaw) Err() error {
return vrr.reader.Err()
}
// Close marks the results as closed, returning any errors that occurred during reading the results.
func (vrr *ViewResultRaw) Close() error {
return vrr.reader.Close()
}
// MetaData returns any meta-data that was available from this query as bytes.
func (vrr *ViewResultRaw) MetaData() ([]byte, error) {
return vrr.reader.MetaData()
}
// ViewResult implements an iterator interface which can be used to iterate over the rows of the query results.
type ViewResult struct {
reader viewRowReader
currentRow ViewRow
jsonErr error
}
func newViewResult(reader viewRowReader) *ViewResult {
return &ViewResult{
reader: reader,
}
}
// Raw returns a ViewResultRaw which can be used to access the raw byte data from view queries.
// Calling this function invalidates the underlying ViewResult which will no longer be able to be used.
// VOLATILE: This API is subject to change at any time.
func (r *ViewResult) Raw() *ViewResultRaw {
vr := &ViewResultRaw{
reader: r.reader,
}
r.reader = nil
return vr
}
// Next assigns the next result from the results into the value pointer, returning whether the read was successful.
func (r *ViewResult) Next() bool {
if r.reader == nil {
return false
}
rowBytes := r.reader.NextRow()
if rowBytes == nil {
return false
}
r.currentRow = ViewRow{}
var rowData jsonViewRow
if err := json.Unmarshal(rowBytes, &rowData); err != nil {
// This should never happen but if it does then lets store it in a best efforts basis and maybe the next
// row will be ok. We can then return this from .Err().
r.jsonErr = err
return true
}
r.currentRow.ID = rowData.ID
r.currentRow.keyBytes = rowData.Key
r.currentRow.valueBytes = rowData.Value
return true
}
// Row returns the contents of the current row.
func (r *ViewResult) Row() ViewRow {
if r.reader == nil {
return ViewRow{}
}
return r.currentRow
}
// Err returns any errors that have occurred on the stream
func (r *ViewResult) Err() error {
if r.reader == nil {
return errors.New("result object is no longer valid")
}
err := r.reader.Err()
if err != nil {
return err
}
return r.jsonErr
}
// Close marks the results as closed, returning any errors that occurred during reading the results.
func (r *ViewResult) Close() error {
if r.reader == nil {
return r.Err()
}
return r.reader.Close()
}
// MetaData returns any meta-data that was available from this query. Note that
// the meta-data will only be available once the object has been closed (either
// implicitly or explicitly).
func (r *ViewResult) MetaData() (*ViewMetaData, error) {
if r.reader == nil {
return nil, r.Err()
}
metaDataBytes, err := r.reader.MetaData()
if err != nil {
return nil, err
}
var jsonResp jsonViewResponse
err = json.Unmarshal(metaDataBytes, &jsonResp)
if err != nil {
return nil, err
}
var metaData ViewMetaData
err = metaData.fromData(jsonResp)
if err != nil {
return nil, err
}
return &metaData, nil
}
// ViewQuery performs a view query and returns a list of rows or an error.
func (b *Bucket) ViewQuery(designDoc string, viewName string, opts *ViewOptions) (*ViewResult, error) {
if opts == nil {
opts = &ViewOptions{}
}
start := time.Now()
defer valueRecord(b.meter, meterValueServiceViews, "views", start)
designDoc = b.maybePrefixDevDocument(opts.Namespace, designDoc)
span := createSpan(b.tracer, opts.ParentSpan, "views", "views")
span.SetAttribute("db.name", b.Name())
span.SetAttribute("db.operation", designDoc+"/"+viewName)
defer span.End()
timeout := opts.Timeout
if timeout == 0 {
timeout = b.timeoutsConfig.ViewTimeout
}
deadline := time.Now().Add(timeout)
retryWrapper := b.retryStrategyWrapper
if opts.RetryStrategy != nil {
retryWrapper = newRetryStrategyWrapper(opts.RetryStrategy)
}
urlValues, err := opts.toURLValues()
if err != nil {
return nil, errors.Wrap(err, "could not parse query options")
}
return b.execViewQuery(span.Context(), "_view", designDoc, viewName, *urlValues, deadline, retryWrapper)
}
func (b *Bucket) execViewQuery(
span RequestSpanContext,
viewType, ddoc, viewName string,
options url.Values,
deadline time.Time,
wrapper *retryStrategyWrapper,
) (*ViewResult, error) {
provider, err := b.connectionManager.getViewProvider(b.Name())
if err != nil {
return nil, ViewError{
InnerError: wrapError(err, "failed to get query provider"),
DesignDocumentName: ddoc,
ViewName: viewName,
}
}
res, err := provider.ViewQuery(gocbcore.ViewQueryOptions{
DesignDocumentName: ddoc,
ViewType: viewType,
ViewName: viewName,
Options: options,
RetryStrategy: wrapper,
Deadline: deadline,
TraceContext: span,
})
if err != nil {
return nil, maybeEnhanceViewError(err)
}
return newViewResult(res), nil
}
func (b *Bucket) maybePrefixDevDocument(namespace DesignDocumentNamespace, ddoc string) string {
designDoc := ddoc
if namespace == DesignDocumentNamespaceProduction {
designDoc = strings.TrimPrefix(ddoc, "dev_")
} else {
if !strings.HasPrefix(ddoc, "dev_") {
designDoc = "dev_" + ddoc
}
}
return designDoc
}