-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb_operations.go
242 lines (190 loc) · 5.5 KB
/
mongodb_operations.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
package gomongo
import (
"context"
"errors"
"fmt"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func where[T any](ctx context.Context, mongoCollection *mongo.Collection, filter any, order map[string]OrderBy) ([]T, error) {
cursor, err := mongoCollection.Find(ctx, filter, options.Find().SetSort(order))
if err != nil {
return nil, err
}
return mongoCursorToSlice[T](ctx, cursor)
}
func mongoCursorToSlice[T any](ctx context.Context, cursor *mongo.Cursor) ([]T, error) {
defer cursor.Close(ctx)
var instanceSlice = []T{}
for cursor.Next(ctx) {
var instance T
err := cursor.Decode(&instance)
if err != nil {
return nil, err
}
instanceSlice = append(instanceSlice, instance)
}
return instanceSlice, nil
}
func findOne[T any](ctx context.Context, mongoCollection *mongo.Collection, filter any, order map[string]OrderBy) (T, error) {
var instance T
result := mongoCollection.FindOne(ctx, filter, options.FindOne().SetSort(order))
if err := singleResultError(result); err != nil {
return instance, err
}
return singleResultToInstance[T](result)
}
func singleResultError(result *mongo.SingleResult) error {
if err := result.Err(); err != nil {
if errors.Is(result.Err(), mongo.ErrNoDocuments) || errors.Is(result.Err(), mongo.ErrNilDocument) {
return ErrDocumentNotFound
}
return err
}
return nil
}
func singleResultToInstance[T any](result *mongo.SingleResult) (T, error) {
var instance T
err := result.Decode(&instance)
return instance, err
}
func create[T any](ctx context.Context, mongoCollection *mongo.Collection, doc T) (ID, error) {
docBSON, err := dataToBSON(doc)
if err != nil {
return nil, err
}
delete(docBSON, "_id")
result, err := mongoCollection.InsertOne(ctx, docBSON)
if err != nil {
return nil, insertOneError(err)
}
return insertOneResultToID(result)
}
func dataToBSON[T any](doc T) (bson.M, error) {
dataMarshal, err := bson.Marshal(doc)
if err != nil {
return nil, fmt.Errorf("convert data: %w", err)
}
var dataBSON bson.M
if err := bson.Unmarshal(dataMarshal, &dataBSON); err != nil {
return nil, fmt.Errorf("convert data: %w", err)
}
return dataBSON, nil
}
func insertOneError(err error) error {
if mongo.IsDuplicateKeyError(err) {
return ErrDuplicateKey
}
return err
}
func insertOneResultToID(result *mongo.InsertOneResult) (ID, error) {
id, ok := result.InsertedID.(primitive.ObjectID)
if !ok {
return nil, fmt.Errorf("cannot convert id to ObjectID")
}
return &id, nil
}
func deleteID(ctx context.Context, mongoCollection *mongo.Collection, filter any) error {
result, err := mongoCollection.DeleteOne(ctx, filter)
if err != nil {
return err
}
if err := deleteResultError(result); err != nil {
return err
}
return nil
}
func deleteResultError(result *mongo.DeleteResult) error {
if result.DeletedCount == 0 {
return ErrDocumentNotFound
}
return nil
}
func updateID[T any](ctx context.Context, mongoCollection *mongo.Collection, filter any, doc T) error {
docBSON, err := dataToBSON(doc)
if err != nil {
return err
}
delete(docBSON, "_id")
update := bson.M{"$set": docBSON}
result, err := mongoCollection.UpdateOne(ctx, filter, update)
if err != nil {
return err
}
if err := updateResultErrors(result); err != nil {
return err
}
return nil
}
func updateResultErrors(result *mongo.UpdateResult) error {
if result.MatchedCount == 0 {
return ErrDocumentNotFound
}
return nil
}
func count(ctx context.Context, mongoCollection *mongo.Collection, filter any) (int, error) {
count, err := mongoCollection.CountDocuments(ctx, filter)
if err != nil {
return 0, err
}
return int(count), nil
}
func createUniqueIndex(ctx context.Context, mongoCollection *mongo.Collection, name string, keys map[string]OrderBy) error {
indexModel := mongo.IndexModel{
Keys: keys,
Options: options.Index().SetUnique(true),
}
if name != "" {
indexModel.Options.SetName(name)
}
_, err := mongoCollection.Indexes().CreateOne(ctx, indexModel)
if err != nil {
return err
}
return nil
}
func listIndexes(ctx context.Context, mongoCollection *mongo.Collection) ([]Index, error) {
cursor, err := mongoCollection.Indexes().List(ctx)
if err != nil {
return nil, err
}
return mongoCursorToSliceIndex(ctx, cursor)
}
func mongoCursorToSliceIndex(ctx context.Context, cursor *mongo.Cursor) ([]Index, error) {
defer cursor.Close(ctx)
var indexes []Index
for cursor.Next(ctx) {
var index Index
err := cursor.Decode(&index)
if err != nil {
return nil, err
}
indexes = append(indexes, index)
}
return indexes, nil
}
func deleteIndex(ctx context.Context, mongoCollection *mongo.Collection, indexName string) error {
_, err := mongoCollection.Indexes().DropOne(ctx, indexName)
if err != nil {
var mongoCommandError mongo.CommandError
if ok := errors.As(err, &mongoCommandError); ok {
return mongoCommandErrorToCustomError(mongoCommandError)
}
return err
}
return nil
}
func mongoCommandErrorToCustomError(mongoCommandError mongo.CommandError) error {
switch mongoCommandError.Code {
case 72:
return fmt.Errorf("%w: %s", ErrInvalidCommandOptions, fmt.Errorf(mongoCommandError.Message))
case 27:
return fmt.Errorf("%w: %s", ErrIndexNotFound, fmt.Errorf(mongoCommandError.Message))
}
return fmt.Errorf("mongo command error: %s: %s", mongoCommandError.Name, mongoCommandError.Message)
}
func drop(ctx context.Context, mongoCollection *mongo.Collection) error {
return mongoCollection.Drop(ctx)
}