forked from mongodb/mongo-go-driver
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index_view.go
271 lines (225 loc) · 6.15 KB
/
index_view.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
// Copyright (C) MongoDB, Inc. 2017-present.
//
// Licensed under the Apache License, Version 2.0 (the "License"); you may
// not use this file except in compliance with the License. You may obtain
// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
package mongo
import (
"bytes"
"context"
"errors"
"fmt"
"github.com/mongodb/mongo-go-driver/bson"
"github.com/mongodb/mongo-go-driver/core/command"
"github.com/mongodb/mongo-go-driver/core/dispatch"
"github.com/mongodb/mongo-go-driver/mongo/indexopt"
)
// ErrInvalidIndexValue indicates that the index Keys document has a value that isn't either a number or a string.
var ErrInvalidIndexValue = errors.New("invalid index value")
// ErrNonStringIndexName indicates that the index name specified in the options is not a string.
var ErrNonStringIndexName = errors.New("index name must be a string")
// ErrMultipleIndexDrop indicates that multiple indexes would be dropped from a call to IndexView.DropOne.
var ErrMultipleIndexDrop = errors.New("multiple indexes would be dropped")
// IndexView is used to create, drop, and list indexes on a given collection.
type IndexView struct {
coll *Collection
}
// IndexModel contains information about an index.
type IndexModel struct {
Keys *bson.Document
Options *bson.Document
}
// List returns a cursor iterating over all the indexes in the collection.
func (iv IndexView) List(ctx context.Context, opts ...indexopt.List) (Cursor, error) {
listOpts, sess, err := indexopt.BundleList(opts...).Unbundle(true)
if err != nil {
return nil, err
}
err = iv.coll.client.ValidSession(sess)
if err != nil {
return nil, err
}
listCmd := command.ListIndexes{
NS: iv.coll.namespace(),
Opts: listOpts,
Session: sess,
Clock: iv.coll.client.clock,
}
return dispatch.ListIndexes(
ctx, listCmd,
iv.coll.client.topology,
iv.coll.writeSelector,
iv.coll.client.id,
iv.coll.client.topology.SessionPool,
)
}
// CreateOne creates a single index in the collection specified by the model.
func (iv IndexView) CreateOne(ctx context.Context, model IndexModel, opts ...indexopt.Create) (string, error) {
names, err := iv.CreateMany(ctx, []IndexModel{model}, opts...)
if err != nil {
return "", err
}
return names[0], nil
}
// CreateMany creates multiple indexes in the collection specified by the models. The names of the
// creates indexes are returned.
func (iv IndexView) CreateMany(ctx context.Context, models []IndexModel, opts ...indexopt.Create) ([]string, error) {
names := make([]string, 0, len(models))
indexes := bson.NewArray()
for _, model := range models {
if model.Keys == nil {
return nil, fmt.Errorf("index model keys cannot be nil")
}
name, err := getOrGenerateIndexName(model)
if err != nil {
return nil, err
}
names = append(names, name)
index := bson.NewDocument(
bson.EC.SubDocument("key", model.Keys),
)
if model.Options != nil {
err = index.Concat(model.Options)
if err != nil {
return nil, err
}
}
index.Set(bson.EC.String("name", name))
indexes.Append(bson.VC.Document(index))
}
createOpts, sess, err := indexopt.BundleCreate(opts...).Unbundle(true)
if err != nil {
return nil, err
}
err = iv.coll.client.ValidSession(sess)
if err != nil {
return nil, err
}
cmd := command.CreateIndexes{
NS: iv.coll.namespace(),
Indexes: indexes,
Opts: createOpts,
Session: sess,
Clock: iv.coll.client.clock,
}
_, err = dispatch.CreateIndexes(
ctx, cmd,
iv.coll.client.topology,
iv.coll.writeSelector,
iv.coll.client.id,
iv.coll.client.topology.SessionPool,
)
if err != nil {
return nil, err
}
return names, nil
}
// DropOne drops the index with the given name from the collection.
func (iv IndexView) DropOne(ctx context.Context, name string, opts ...indexopt.Drop) (bson.Reader, error) {
if name == "*" {
return nil, ErrMultipleIndexDrop
}
dropOpts, sess, err := indexopt.BundleDrop(opts...).Unbundle(true)
if err != nil {
return nil, err
}
err = iv.coll.client.ValidSession(sess)
if err != nil {
return nil, err
}
cmd := command.DropIndexes{
NS: iv.coll.namespace(),
Index: name,
Opts: dropOpts,
Session: sess,
Clock: iv.coll.client.clock,
}
return dispatch.DropIndexes(
ctx, cmd,
iv.coll.client.topology,
iv.coll.writeSelector,
iv.coll.client.id,
iv.coll.client.topology.SessionPool,
)
}
// DropAll drops all indexes in the collection.
func (iv IndexView) DropAll(ctx context.Context, opts ...indexopt.Drop) (bson.Reader, error) {
dropOpts, sess, err := indexopt.BundleDrop(opts...).Unbundle(true)
if err != nil {
return nil, err
}
err = iv.coll.client.ValidSession(sess)
if err != nil {
return nil, err
}
cmd := command.DropIndexes{
NS: iv.coll.namespace(),
Index: "*",
Opts: dropOpts,
Session: sess,
Clock: iv.coll.client.clock,
}
return dispatch.DropIndexes(
ctx, cmd,
iv.coll.client.topology,
iv.coll.writeSelector,
iv.coll.client.id,
iv.coll.client.topology.SessionPool,
)
}
func getOrGenerateIndexName(model IndexModel) (string, error) {
if model.Options != nil {
nameVal, err := model.Options.LookupErr("name")
switch err {
case bson.ErrElementNotFound:
break
case nil:
if nameVal.Type() != bson.TypeString {
return "", ErrNonStringIndexName
}
return nameVal.StringValue(), nil
default:
return "", err
}
}
name := bytes.NewBufferString("")
itr := model.Keys.Iterator()
first := true
for itr.Next() {
if !first {
_, err := name.WriteRune('_')
if err != nil {
return "", err
}
}
elem := itr.Element()
_, err := name.WriteString(elem.Key())
if err != nil {
return "", err
}
_, err = name.WriteRune('_')
if err != nil {
return "", err
}
var value string
switch elem.Value().Type() {
case bson.TypeInt32:
value = fmt.Sprintf("%d", elem.Value().Int32())
case bson.TypeInt64:
value = fmt.Sprintf("%d", elem.Value().Int64())
case bson.TypeString:
value = elem.Value().StringValue()
default:
return "", ErrInvalidIndexValue
}
_, err = name.WriteString(value)
if err != nil {
return "", err
}
first = false
}
if err := itr.Err(); err != nil {
return "", err
}
return name.String(), nil
}