forked from mrz1836/go-datastore
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmongodb.go
582 lines (496 loc) · 15 KB
/
mongodb.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
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
package datastore
import (
"context"
"encoding/json"
"errors"
"fmt"
"reflect"
"time"
"github.com/newrelic/go-agent/v3/integrations/nrmongo"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
const (
logLine = "MONGO %s %s: %+v\n"
logErrorLine = "MONGO %s %s: %e: %+v\n"
)
// saveWithMongo will save a given struct to MongoDB
func (c *Client) saveWithMongo(
ctx context.Context,
model interface{},
newRecord bool,
) (err error) {
collectionName := GetModelTableName(model)
if collectionName == nil {
return ErrUnknownCollection
}
// Set the collection
collection := c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, *collectionName),
)
// Create or update
if newRecord {
c.DebugLog(ctx, fmt.Sprintf(logLine, "insert", *collectionName, model))
_, err = collection.InsertOne(ctx, model)
} else {
id := GetModelStringAttribute(model, sqlIDFieldProper)
update := bson.M{conditionSet: model}
unset := GetModelUnset(model)
if len(unset) > 0 {
update = bson.M{conditionSet: model, conditionUnSet: unset}
}
c.DebugLog(ctx, fmt.Sprintf(logLine, "update", *collectionName, model))
_, err = collection.UpdateOne(
ctx, bson.M{mongoIDField: *id}, update,
)
}
// Check for duplicate key (insert error, record exists)
if mongo.IsDuplicateKeyError(err) {
c.DebugLog(ctx, fmt.Sprintf(logErrorLine, "error", *collectionName, ErrDuplicateKey, model))
return ErrDuplicateKey
}
if err != nil {
c.DebugLog(ctx, fmt.Sprintf(logErrorLine, "error", *collectionName, err, model))
}
return
}
// incrementWithMongo will save a given struct to MongoDB
func (c *Client) incrementWithMongo(
ctx context.Context,
model interface{},
fieldName string,
increment int64,
) (newValue int64, err error) {
collectionName := GetModelTableName(model)
if collectionName == nil {
return newValue, ErrUnknownCollection
}
// Set the collection
collection := c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, *collectionName),
)
id := GetModelStringAttribute(model, sqlIDFieldProper)
if id == nil {
return newValue, errors.New("can only increment by " + sqlIDField)
}
update := bson.M{conditionIncrement: bson.M{fieldName: increment}}
c.DebugLog(ctx, fmt.Sprintf(logLine, "increment", *collectionName, model))
result := collection.FindOneAndUpdate(
ctx, bson.M{mongoIDField: *id}, update,
)
if result.Err() != nil {
return newValue, result.Err()
}
var rawValue bson.Raw
if rawValue, err = result.DecodeBytes(); err != nil {
return
}
var newModel map[string]interface{}
_ = bson.Unmarshal(rawValue, &newModel) // todo: cannot check error, breaks code atm
newValue = newModel[fieldName].(int64) + increment
if err != nil {
c.DebugLog(ctx, fmt.Sprintf(logErrorLine, "error", *collectionName, err, model))
}
return
}
// CreateInBatchesMongo insert multiple models vai bulk.Write
func (c *Client) CreateInBatchesMongo(
ctx context.Context,
models interface{},
batchSize int,
) error {
collectionName := GetModelTableName(models)
if collectionName == nil {
return ErrUnknownCollection
}
mongoModels := make([]mongo.WriteModel, 0)
collection := c.GetMongoCollection(*collectionName)
bulkOptions := options.BulkWrite().SetOrdered(true)
count := 0
if reflect.TypeOf(models).Kind() == reflect.Slice {
s := reflect.ValueOf(models)
for i := 0; i < s.Len(); i++ {
m := mongo.NewInsertOneModel()
m.SetDocument(s.Index(i).Interface())
mongoModels = append(mongoModels, m)
count++
if count%batchSize == 0 {
_, err := collection.BulkWrite(ctx, mongoModels, bulkOptions)
if err != nil {
return err
}
// reset the bulk
mongoModels = make([]mongo.WriteModel, 0)
}
}
}
if count%batchSize != 0 {
_, err := collection.BulkWrite(ctx, mongoModels, bulkOptions)
if err != nil {
return err
}
}
return nil
}
// getWithMongo will get given struct(s) from MongoDB
func (c *Client) getWithMongo(
ctx context.Context,
models interface{},
conditions map[string]interface{},
fieldResult interface{},
queryParams *QueryParams,
) error {
queryConditions := getMongoQueryConditions(models, conditions, c.GetMongoConditionProcessor())
collectionName := GetModelTableName(models)
if collectionName == nil {
return ErrUnknownCollection
}
// Set the collection
collection := c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, *collectionName),
)
var fields []string
if fieldResult != nil {
fields = getFieldNames(fieldResult)
}
if IsModelSlice(models) {
c.DebugLog(ctx, fmt.Sprintf(logLine, "findMany", *collectionName, queryConditions))
var opts []*options.FindOptions
if fields != nil {
projection := bson.D{}
for _, field := range fields {
projection = append(projection, bson.E{Key: field, Value: 1})
}
opts = append(opts, options.Find().SetProjection(projection))
}
if queryParams.Page > 0 {
opts = append(opts, options.Find().SetLimit(int64(queryParams.PageSize)).SetSkip(int64(queryParams.PageSize*(queryParams.Page-1))))
}
if queryParams.OrderByField == sqlIDField {
queryParams.OrderByField = mongoIDField // use Mongo _id instead of default id field
}
if queryParams.OrderByField != "" {
sortOrder := 1
if queryParams.SortDirection == SortDesc {
sortOrder = -1
}
opts = append(opts, options.Find().SetSort(bson.D{{Key: queryParams.OrderByField, Value: sortOrder}}))
}
cursor, err := collection.Find(ctx, queryConditions, opts...)
if err != nil {
return err
}
if err = cursor.Err(); errors.Is(err, mongo.ErrNoDocuments) {
return ErrNoResults
} else if err != nil {
return cursor.Err()
}
if fieldResult != nil {
if err = cursor.All(ctx, fieldResult); err != nil {
return err
}
} else {
if err = cursor.All(ctx, models); err != nil {
return err
}
}
} else {
c.DebugLog(ctx, fmt.Sprintf(logLine, "find", *collectionName, queryConditions))
var opts []*options.FindOneOptions
if fields != nil {
projection := bson.D{}
for _, field := range fields {
projection = append(projection, bson.E{Key: field, Value: 1})
}
opts = append(opts, options.FindOne().SetProjection(projection))
}
result := collection.FindOne(ctx, queryConditions, opts...)
if err := result.Err(); errors.Is(err, mongo.ErrNoDocuments) {
c.DebugLog(ctx, fmt.Sprintf(logLine, "result", *collectionName, "no result"))
return ErrNoResults
} else if err != nil {
c.DebugLog(ctx, fmt.Sprintf(logLine, "result error", *collectionName, err))
return result.Err()
}
if fieldResult != nil {
if err := result.Decode(fieldResult); err != nil {
c.DebugLog(ctx, fmt.Sprintf(logLine, "result error", *collectionName, err))
return err
}
} else {
if err := result.Decode(models); err != nil {
c.DebugLog(ctx, fmt.Sprintf(logLine, "result error", *collectionName, err))
return err
}
}
}
return nil
}
// countWithMongo will get a count of all models matching the conditions
func (c *Client) countWithMongo(
ctx context.Context,
models interface{},
conditions map[string]interface{},
) (int64, error) {
queryConditions := getMongoQueryConditions(models, conditions, c.GetMongoConditionProcessor())
collectionName := GetModelTableName(models)
if collectionName == nil {
return 0, ErrUnknownCollection
}
// Set the collection
collection := c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, *collectionName),
)
c.DebugLog(ctx, fmt.Sprintf(logLine, accumulationCountField, *collectionName, queryConditions))
count, err := collection.CountDocuments(ctx, queryConditions)
if err != nil {
return 0, err
}
return count, nil
}
// aggregateWithMongo will get a count of all models aggregate by aggregateColumn matching the conditions
func (c *Client) aggregateWithMongo(
ctx context.Context,
models interface{},
conditions map[string]interface{},
aggregateColumn string,
timeout time.Duration,
) (map[string]interface{}, error) {
queryConditions := getMongoQueryConditions(models, conditions, c.GetMongoConditionProcessor())
collectionName := GetModelTableName(models)
if collectionName == nil {
return nil, ErrUnknownCollection
}
// Set the collection
collection := c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, *collectionName),
)
c.DebugLog(ctx, fmt.Sprintf(logLine, accumulationCountField, *collectionName, queryConditions))
// Marshal the data
var matchStage bson.D
data, err := bson.Marshal(queryConditions)
if err != nil {
return nil, err
}
// Unmarshal the bson
if err = bson.Unmarshal(data, &matchStage); err != nil {
return nil, err
}
aggregateOn := bson.E{
Key: mongoIDField,
Value: "$" + aggregateColumn,
} // default
// Check for date field
if StringInSlice(aggregateColumn, DateFields) {
aggregateOn = bson.E{
Key: mongoIDField,
Value: bson.D{{
Key: conditionDateToString,
Value: bson.D{
{Key: "format", Value: "%Y%m%d"},
{Key: "date", Value: "$" + aggregateColumn},
}},
},
}
}
// Grouping
groupStage := bson.D{{Key: conditionGroup, Value: bson.D{
aggregateOn, {
Key: accumulationCountField,
Value: bson.D{{
Key: conditionSum,
Value: 1,
}},
},
}}}
pipeline := mongo.Pipeline{
bson.D{
{Key: conditionMatch, Value: matchStage},
}, groupStage}
// anonymous struct for unmarshalling result bson
var results []struct {
ID string `bson:"_id"`
Count int64 `bson:"count"`
}
var aggregateCursor *mongo.Cursor
aggregateCtx, cancel := context.WithTimeout(ctx, timeout)
defer cancel()
// Get the aggregation
if aggregateCursor, err = collection.Aggregate(
aggregateCtx, pipeline,
); err != nil {
return nil, err
}
// Cursor: All
if err = aggregateCursor.All(ctx, &results); err != nil {
return nil, err
}
// Create the result
aggregateResult := make(map[string]interface{})
for _, result := range results {
aggregateResult[result.ID] = result.Count
}
return aggregateResult, nil
}
// GetMongoCollection will get the mongo collection for the given tableName
func (c *Client) GetMongoCollection(
collectionName string,
) *mongo.Collection {
return c.options.mongoDB.Collection(
setPrefix(c.options.mongoDBConfig.TablePrefix, collectionName),
)
}
// GetMongoCollectionByTableName will get the mongo collection for the given tableName
func (c *Client) GetMongoCollectionByTableName(
tableName string,
) *mongo.Collection {
return c.options.mongoDB.Collection(tableName)
}
// getFieldNames will get the field names in a slice of strings
func getFieldNames(fieldResult interface{}) []string {
if fieldResult == nil {
return []string{}
}
fields := make([]string, 0)
model := reflect.ValueOf(fieldResult)
if model.Kind() == reflect.Ptr {
model = model.Elem()
}
if model.Kind() == reflect.Slice {
elemType := model.Type().Elem()
fmt.Println(elemType.Kind())
if elemType.Kind() == reflect.Ptr {
model = reflect.New(elemType.Elem())
} else {
model = reflect.New(elemType)
}
}
if model.Kind() == reflect.Ptr {
model = model.Elem()
}
for i := 0; i < model.Type().NumField(); i++ {
field := model.Type().Field(i)
fields = append(fields, field.Tag.Get(bsonTagName))
}
return fields
}
// setPrefix will automatically append the table prefix if found
func setPrefix(prefix, collection string) string {
if len(prefix) > 0 {
return prefix + "_" + collection
}
return collection
}
// getMongoQueryConditions will build the Mongo query conditions
// this functions tries to mimic the way gorm generates a where clause (naively)
func getMongoQueryConditions(
model interface{},
conditions map[string]interface{},
customProcessor func(conditions *map[string]interface{}),
) map[string]interface{} {
if conditions == nil {
conditions = map[string]interface{}{}
} else {
// check for id field
_, ok := conditions[sqlIDField]
if ok {
conditions[mongoIDField] = conditions[sqlIDField]
delete(conditions, sqlIDField)
}
processMongoConditions(&conditions, customProcessor)
}
// add model ID to the query conditions, if set on the model
id := GetModelStringAttribute(model, sqlIDFieldProper)
if id != nil && *id != "" {
conditions[mongoIDField] = *id
}
return conditions
}
// processMongoConditions will process all conditions for Mongo, including custom processing
func processMongoConditions(conditions *map[string]interface{},
customProcessor func(conditions *map[string]interface{})) *map[string]interface{} {
// Transform the id field to mongo _id field
_, ok := (*conditions)[sqlIDField]
if ok {
(*conditions)[mongoIDField] = (*conditions)[sqlIDField]
delete(*conditions, sqlIDField)
}
// Transform the map of metadata to key / value query
_, ok = (*conditions)[metadataField]
if ok {
processMetadataConditions(conditions)
}
// Do we have a custom processor?
if customProcessor != nil {
customProcessor(conditions)
}
// Handle all conditions post-processing
for key, condition := range *conditions {
if key == conditionAnd || key == conditionOr {
var slice []map[string]interface{}
a, _ := json.Marshal(condition) //nolint:errchkjson // this check might break the current code
_ = json.Unmarshal(a, &slice)
var newConditions []map[string]interface{}
for _, c := range slice {
newConditions = append(newConditions, *processMongoConditions(&c, customProcessor)) //nolint:scopelint,gosec // ignore for now
}
(*conditions)[key] = newConditions
}
}
return conditions
}
// processMetadataConditions will process metadata conditions
func processMetadataConditions(conditions *map[string]interface{}) {
// marshal / unmarshal into standard map[string]interface{}
m, _ := json.Marshal((*conditions)[metadataField]) //nolint:errchkjson // this check might break the current code
var r map[string]interface{}
_ = json.Unmarshal(m, &r)
// Loop and create the key associations
metadata := make([]map[string]interface{}, 0)
for key, value := range r {
metadata = append(metadata, map[string]interface{}{
metadataField + ".k": key,
metadataField + ".v": value,
})
}
// Found some metadata
if len(metadata) > 0 {
_, ok := (*conditions)[conditionAnd]
if ok {
and := (*conditions)[conditionAnd].([]map[string]interface{})
and = append(and, metadata...)
(*conditions)[conditionAnd] = and
} else {
(*conditions)[conditionAnd] = metadata
}
}
// Remove the field from conditions
delete(*conditions, metadataField)
}
// openMongoDatabase will open a new database or use an existing connection
func openMongoDatabase(ctx context.Context, config *MongoDBConfig) (*mongo.Database, error) {
// Use an existing connection
if config.ExistingConnection != nil {
return config.ExistingConnection, nil
}
// Create the new client
nrMon := nrmongo.NewCommandMonitor(nil)
client, err := mongo.Connect(
ctx,
options.Client().SetMonitor(nrMon),
options.Client().ApplyURI(config.URI),
)
if err != nil {
return nil, err
}
// Check the connection
if err = client.Ping(ctx, readpref.Primary()); err != nil {
return nil, err
}
// Return the client
return client.Database(
config.DatabaseName,
), nil
}