2023-07-17 12:48:36 +01:00
|
|
|
package dbAccess
|
2023-07-15 22:32:46 +01:00
|
|
|
|
|
|
|
import (
|
2024-03-25 12:21:59 +00:00
|
|
|
"git.fjla.uk/owlboard/timetable-mgr/helpers"
|
2024-03-25 11:26:07 +00:00
|
|
|
"git.fjla.uk/owlboard/timetable-mgr/log"
|
2023-07-15 23:00:48 +01:00
|
|
|
|
2023-07-15 22:32:46 +01:00
|
|
|
"context"
|
|
|
|
"fmt"
|
2023-07-18 00:25:13 +01:00
|
|
|
"time"
|
2023-07-15 22:32:46 +01:00
|
|
|
|
2023-07-18 00:25:13 +01:00
|
|
|
"go.mongodb.org/mongo-driver/mongo"
|
|
|
|
"go.mongodb.org/mongo-driver/mongo/options"
|
2023-07-15 22:32:46 +01:00
|
|
|
)
|
|
|
|
|
2024-03-26 16:32:00 +00:00
|
|
|
const databaseName string = "owlboard"
|
|
|
|
const CorpusCollection string = "corpus"
|
|
|
|
const StationsCollection string = "stations"
|
|
|
|
const metaCollection string = "meta"
|
2024-03-26 22:33:11 +00:00
|
|
|
const TimetableCollection string = "timetable"
|
2024-03-26 16:32:00 +00:00
|
|
|
|
2024-03-25 12:21:59 +00:00
|
|
|
// Provide the DB Connection to other functions
|
|
|
|
var MongoClient (*mongo.Client)
|
2023-07-18 00:25:13 +01:00
|
|
|
|
2024-03-25 12:21:59 +00:00
|
|
|
func getDbUri(cfg *helpers.Configuration) string {
|
|
|
|
var uri = "mongodb://" + cfg.DbUser + ":" + cfg.DbPass + "@" + cfg.DbHost + ":" + cfg.DbPort
|
2023-07-18 00:25:13 +01:00
|
|
|
return uri
|
|
|
|
}
|
|
|
|
|
2023-07-27 21:11:08 +01:00
|
|
|
// Configure bsonOpts
|
|
|
|
var bsonOpts = &options.BSONOptions{
|
|
|
|
UseJSONStructTags: true,
|
|
|
|
}
|
|
|
|
|
2023-07-15 23:00:48 +01:00
|
|
|
// Initialise the DB Connection
|
2024-03-25 12:21:59 +00:00
|
|
|
func InitDataAccess(cfg *helpers.Configuration) {
|
|
|
|
uri := getDbUri(cfg)
|
2023-07-18 00:25:13 +01:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
2024-03-25 12:21:59 +00:00
|
|
|
client, err := mongo.Connect(ctx, options.Client().ApplyURI(uri).SetBSONOptions(bsonOpts))
|
2023-07-18 00:25:13 +01:00
|
|
|
if err != nil {
|
2023-07-15 22:32:46 +01:00
|
|
|
fmt.Println(err)
|
2023-07-18 14:09:28 +01:00
|
|
|
log.Msg.Fatal("Error connecting to database: " + err.Error())
|
2023-07-18 00:25:13 +01:00
|
|
|
} else {
|
2023-07-19 01:18:55 +01:00
|
|
|
log.Msg.Info("Database connection successful")
|
2023-07-18 00:25:13 +01:00
|
|
|
}
|
2024-03-25 12:21:59 +00:00
|
|
|
MongoClient = client
|
2023-07-18 00:25:13 +01:00
|
|
|
}
|
2023-07-21 10:02:55 +01:00
|
|
|
|
|
|
|
func CloseMongoClient() {
|
|
|
|
if MongoClient != nil {
|
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
|
|
|
|
defer cancel()
|
|
|
|
if err := MongoClient.Disconnect(ctx); err != nil {
|
|
|
|
log.Msg.Warn("Error disconnecting MongoDB client: " + err.Error())
|
|
|
|
} else {
|
|
|
|
log.Msg.Info("MongoDB client disconnected.")
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}
|