timetable-mgr/dbAccess/pis.go

89 lines
2.0 KiB
Go
Raw Permalink Normal View History

2024-05-02 15:35:00 +01:00
package dbAccess
import (
"context"
"errors"
2024-10-23 11:42:47 +01:00
"time"
2024-05-02 15:35:00 +01:00
"git.fjla.uk/owlboard/go-types/pkg/database"
2024-10-23 11:42:47 +01:00
"git.fjla.uk/owlboard/timetable-mgr/log"
2024-05-02 15:35:00 +01:00
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/mongo"
2024-10-23 11:42:47 +01:00
"go.mongodb.org/mongo-driver/mongo/options"
"go.uber.org/zap"
2024-05-02 15:35:00 +01:00
)
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
}
2024-10-23 11:42:47 +01:00
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")
2024-10-23 11:42:47 +01:00
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")
2024-10-23 11:42:47 +01:00
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
}