-
Notifications
You must be signed in to change notification settings - Fork 1
/
mongodb.go
518 lines (428 loc) · 16 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
package documents
import (
"context"
"fmt"
"time"
"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"
// "github.com/mdaxf/iac/com"
"github.com/mdaxf/iac/logger"
// "github.com/mdaxf/iac/framework/documentdb/mongodb"
)
type DocDB struct {
MongoDBClient *mongo.Client
MongoDBDatabase *mongo.Database
MongoDBCollection_TC *mongo.Collection
/*
*/
DatabaseType string
DatabaseConnection string
DatabaseName string
iLog logger.Log
monitoring bool
}
/*
var DatabaseType = "mongodb"
var DatabaseConnection = "mongodb://localhost:27017"
var DatabaseName = "IAC_CFG"
*/
// InitMongoDB initializes a MongoDB connection and returns a DocDB object.
// It takes two parameters: DatabaseConnection (the MongoDB connection string) and DatabaseName (the name of the database).
// It returns a pointer to a DocDB object and an error if any.
// The function logs the performance duration and recovers from any panics.
func InitMongoDB(DatabaseConnection string, DatabaseName string) (*DocDB, error) {
iLog := logger.Log{ModuleName: logger.Framework, User: "System", ControllerName: "MongoDB Connection"}
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
iLog.PerformanceWithDuration("documents.InitMongoDB", elapsed)
}()
defer func() {
if err := recover(); err != nil {
iLog.Error(fmt.Sprintf("There is error to documents.InitMongoDB with error: %s", err))
return
}
}()
doc := &DocDB{
DatabaseConnection: DatabaseConnection,
DatabaseName: DatabaseName,
iLog: iLog,
monitoring: false,
}
_, err := doc.ConnectMongoDB()
if err != nil {
iLog.Error(fmt.Sprintf("There is error to connect to MongoDB with error: %s", err))
return doc, err
}
if doc.monitoring == false {
go func() {
doc.MonitorAndReconnect()
}()
}
return doc, nil
}
// ConnectMongoDB establishes a connection to the MongoDB database.
// It returns a pointer to the DocDB struct and an error if any.
func (doc *DocDB) ConnectMongoDB() (*DocDB, error) {
// Measure the execution time of the function
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.ConnectMongoDB", elapsed)
}()
// Recover from any panics and log the error
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.ConnectMongoDB with error: %s", err))
return
}
}()
/*
myMongodb := &mongodb.MyDocDB{
DatabaseConnection: doc.DatabaseConnection,
DatabaseName: doc.DatabaseName,
}
err := myMongodb.Connect()
if err != nil {
doc.iLog.Error(fmt.Sprintf("There os error to connect to MongoDB %s %s", doc.DatabaseConnection, doc.DatabaseName))
return nil, err
}
doc.MongoDBClient = myMongodb.MongoDBClient
doc.MongoDBDatabase = myMongodb.MongoDBDatabase
com.IACDocDBConn = &com.DocDB{
DatabaseConnection: myMongodb.DatabaseConnection,
DatabaseName: myMongodb.DatabaseName,
MongoDBClient: myMongodb.MongoDBClient,
MongoDBDatabase: myMongodb.MongoDBDatabase}
return doc, nil */
// Log the database connection details
doc.iLog.Info(fmt.Sprintf("Connect Database: %s %s", doc.DatabaseType, doc.DatabaseConnection))
var err error
// Create a new MongoDB client
doc.MongoDBClient, err = mongo.NewClient(options.Client().ApplyURI(doc.DatabaseConnection))
if err != nil {
doc.iLog.Critical(fmt.Sprintf("failed to connect mongodb with error: %s", err))
return doc, err
}
// Create a context with a timeout
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
// Connect to the MongoDB server
err = doc.MongoDBClient.Connect(ctx)
if err != nil {
doc.iLog.Critical(fmt.Sprintf("failed to connect mongodb with error: %s", err))
return doc, err
}
// Set the MongoDB database
doc.MongoDBDatabase = doc.MongoDBClient.Database(doc.DatabaseName)
// if doc.monitoring == false {
// doc.monitorAndReconnect()
// }
err = doc.MongoDBClient.Ping(context.Background(), nil)
if err != nil {
doc.iLog.Critical(fmt.Sprintf("failed to connect mongodb with error: %s", err))
return doc, err
}
return doc, err
}
func (doc *DocDB) MonitorAndReconnect() {
// Function execution logging
// iLog := logger.Log{ModuleName: logger.Framework, User: "System", ControllerName: "MongoDB.monitorAndReconnect"}
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("MongoDB.monitorAndReconnect", elapsed)
}()
// Recover from any panics and log the error
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("monitorAndReconnect defer error: %s", err))
// ctx.JSON(http.StatusBadRequest, gin.H{"error": err})
}
}()
doc.monitoring = true
for {
err := doc.MongoDBClient.Ping(context.Background(), nil)
if err != nil {
doc.iLog.Error(fmt.Sprintf("MongoDB connection lost with ping error %v, reconnecting...", err))
_, err := doc.ConnectMongoDB()
if err != nil {
doc.iLog.Error(fmt.Sprintf("Failed to reconnect to MongoDB %s with error:%v", doc.DatabaseConnection, err))
time.Sleep(5 * time.Second) // Wait before retrying
continue
} else {
time.Sleep(1 * time.Second)
doc.iLog.Debug(fmt.Sprintf("MongoDB reconnected successfully"))
continue
}
} else {
time.Sleep(1 * time.Second) // Check connection every 60 seconds
continue
}
}
}
// QueryCollection queries a MongoDB collection with the specified filter and projection.
// It returns an array of documents that match the filter, along with any error that occurred.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to query the collection.
func (doc *DocDB) QueryCollection(collectionname string, filter bson.M, projection bson.M) ([]bson.M, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.QueryCollection", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.QueryCollection with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
options := options.Find()
options.SetProjection(projection)
cursor, err := MongoDBCollection.Find(context.TODO(), filter, options)
if err != nil {
doc.iLog.Critical(fmt.Sprintf("failed to get data from collection with error: %s", err))
}
defer cursor.Close(context.Background())
var results []bson.M
for cursor.Next(context.Background()) {
var result bson.M
err := cursor.Decode(&result)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to decode data from collection with error: %s", err))
return nil, err
}
results = append(results, result)
}
if err := cursor.Err(); err != nil {
doc.iLog.Error(fmt.Sprintf("failed to get data from collection with error: %s", err))
return nil, err
}
return results, nil
}
func (doc *DocDB) GetItembyUUID(collectionname string, uuid string) (bson.M, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.GetDefaultItembyName", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.GetDefaultItembyName with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
filter := bson.M{"uuid": uuid}
doc.iLog.Debug(fmt.Sprintf("GetDefaultItembyName: %s from collection:%s", filter, collectionname))
//var result bson.Raw
var result bson.M
err := MongoDBCollection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to get data from collection with error: %s", err))
}
doc.iLog.Debug(fmt.Sprintf("GetDefaultItembyName: %s", result))
return result, err
}
// GetDefaultItembyName retrieves the default item from the specified collection by name.
// It takes the collection name and the name of the item as input parameters.
// It returns the retrieved item as a bson.M object and an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to query the collection.
func (doc *DocDB) GetDefaultItembyName(collectionname string, name string) (bson.M, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.GetDefaultItembyName", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.GetDefaultItembyName with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
filter := bson.M{"name": name, "isdefault": true}
doc.iLog.Debug(fmt.Sprintf("GetDefaultItembyName: %s from collection:%s", filter, collectionname))
//var result bson.Raw
var result bson.M
err := MongoDBCollection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to get data from collection with error: %s", err))
}
doc.iLog.Debug(fmt.Sprintf("GetDefaultItembyName: %s", result))
return result, err
}
// GetItembyID retrieves an item from the specified collection by its ID.
// It takes the collection name and the ID as parameters.
// It returns the item as a bson.M object and an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to query the collection.
func (doc *DocDB) GetItembyID(collectionname string, id string) (bson.M, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.GetItembyID", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.GetItembyID with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
objectid, err := primitive.ObjectIDFromHex(id)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to convert id to objectid with error: %s", err))
}
filter := bson.M{"_id": objectid}
doc.iLog.Debug(fmt.Sprintf("GetItembyID: %s from collection:%s", filter, collectionname))
//var result bson.Raw
var result bson.M
err = MongoDBCollection.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to get data from collection with error: %s", err))
}
doc.iLog.Debug(fmt.Sprintf("GetItembyID: %s", result))
/*
jsonBytes, err := bson.MarshalExtJSON(result, true, false)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to convert data to json with error: %s", err))
}
jsonString := string(jsonBytes)
doc.iLog.Debug(fmt.Sprintf("GetItembyID result: %s", jsonString))
*/
return result, err
}
// GetItembyName retrieves an item from the specified collection by its name.
// It takes the collection name and the name as parameters.
// It returns the item as a bson.M object and an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to query the collection.
func (doc *DocDB) UpdateCollection(collectionname string, filter bson.M, update bson.M, idata interface{}) error {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.UpdateCollection", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.UpdateCollection with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
if update == nil && idata != nil {
data, err := doc.convertToBsonM(idata)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to update data from collection with error: %s", err))
return err
}
_, err = MongoDBCollection.ReplaceOne(context.Background(), filter, data)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to update data from collection with error: %s", err))
}
return err
} else {
_, err := MongoDBCollection.UpdateOne(context.Background(), filter, update)
if err != nil {
doc.iLog.Critical(fmt.Sprintf("failed to update data from collection with error: %s", err))
}
return err
}
}
// InsertCollection inserts a new item into the specified collection.
// It takes the collection name and the item as parameters.
// It returns the result of the insert operation and an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to insert the item into the collection.
func (doc *DocDB) InsertCollection(collectionname string, idata interface{}) (*mongo.InsertOneResult, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.InsertCollection", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.InsertCollection with error: %s", err))
return
}
}()
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
data, err := doc.convertToBsonM(idata)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to update data from collection with error: %s", err))
return nil, err
}
insertResult, err := MongoDBCollection.InsertOne(context.Background(), data)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to insert data from collection with error: %s", err))
}
return insertResult, err
}
// DeleteItemFromCollection deletes an item from the specified collection by its ID.
// It takes the collection name and the ID as parameters.
// It returns an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to delete the item from the collection.
func (doc *DocDB) DeleteItemFromCollection(collectionname string, documentid string) error {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.DeleteItemFromCollection", elapsed)
}()
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.DeleteItemFromCollection with error: %s", err))
return
}
}()
doc.iLog.Debug(fmt.Sprintf("Delete the item %s from collection %s", documentid, collectionname))
MongoDBCollection := doc.MongoDBDatabase.Collection(collectionname)
objectid, err := primitive.ObjectIDFromHex(documentid)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to convert id to objectid with error: %s", err))
return err
}
filter := bson.M{"_id": objectid}
_, err = MongoDBCollection.DeleteOne(context.Background(), filter)
if err != nil {
doc.iLog.Error(fmt.Sprintf("Delete the item %s from collection %s error %s!", documentid, collectionname, err))
return err
}
return nil
}
// DeleteCollection deletes a collection from the MongoDB database.
// It takes the collection name as a parameter.
// It returns an error if any.
// The function logs the performance duration and recovers from any panics.
// The function uses the MongoDB Go driver to delete the collection.
func (doc *DocDB) convertToBsonM(data interface{}) (bson.M, error) {
startTime := time.Now()
defer func() {
elapsed := time.Since(startTime)
doc.iLog.PerformanceWithDuration("documents.convertToBsonM", elapsed)
}()
/*
defer func() {
if err := recover(); err != nil {
doc.iLog.Error(fmt.Sprintf("There is error to documents.convertToBsonM with error: %s", err))
return
}
}()
*/dataBytes, err := bson.Marshal(data)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to convert data to bson.M with error: %s", err))
return nil, err
}
var dataBsonM bson.M
err = bson.Unmarshal(dataBytes, &dataBsonM)
if err != nil {
doc.iLog.Error(fmt.Sprintf("failed to convert data to bson.M with error: %s", err))
return nil, err
}
return dataBsonM, nil
}