timetable-mgr/dbAccess/pis.go
Fred Boniface d35a2a010e
All checks were successful
Go Test / test (push) Successful in 1m40s
Temporarily deploy PIS data to testing collection
2024-11-13 00:28:11 +00:00

89 lines
2.0 KiB
Go

package dbAccess
import (
"context"
"errors"
"time"
"git.fjla.uk/owlboard/go-types/pkg/database"
"git.fjla.uk/owlboard/timetable-mgr/log"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
)
func GetPisMetadata() (*database.PisMetadata, error) {
coll := MongoClient.Database(DatabaseName).Collection(MetaCollection)
filter := bson.M{"type": "PisMetadata"}
var result database.PisMetadata
err := coll.FindOne(context.Background(), filter).Decode(&result)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, nil
}
return nil, err
}
return &result, nil
}
func PutPisMetadata(version string) error {
coll := MongoClient.Database(DatabaseName).Collection(MetaCollection)
options := options.Update().SetUpsert(true)
filter := bson.M{"type": "PisMetadata"}
update := bson.M{
"$set": bson.M{
"type": "PisMetadata",
"lastUpdate": time.Now().Format(time.RFC3339),
"lastVersion": version,
},
}
_, err := coll.UpdateOne(context.Background(), filter, update, options)
if err != nil {
return err
}
log.Info("New Stations Metadata written", zap.String("version", version))
return nil
}
// Puts complete PIS dataset to database
func PutPisData(pis *[]database.PIS) (int64, error) {
coll := MongoClient.Database(DatabaseName).Collection("pis_testing")
var docs []interface{}
for _, entry := range *pis {
docs = append(docs, entry)
}
res, err := coll.InsertMany(context.TODO(), docs)
if err != nil {
return 0, err
}
return int64(len(res.InsertedIDs)), nil
}
func CreatePisIndeces() error {
coll := MongoClient.Database(DatabaseName).Collection("pis_testing")
crsIndex := mongo.IndexModel{
Keys: bson.D{{"stops", 1}},
}
tiplocIndex := mongo.IndexModel{
Keys: bson.D{{"tiplocs", 1}},
}
_, err := coll.Indexes().CreateMany(context.Background(), []mongo.IndexModel{crsIndex, tiplocIndex})
if err != nil {
return err
}
return nil
}