From b29fbb407dc0709d9f0305882d127f06cf4ea380 Mon Sep 17 00:00:00 2001 From: Frank Elsinga Date: Tue, 19 Sep 2023 17:31:24 +0200 Subject: [PATCH 1/2] fixed the eazy cases where connection handling can be added --- server/backend/cafeteriaService.go | 134 +++++++++++++++-------------- server/backend/canteenHeadCount.go | 4 +- server/backend/news.go | 4 +- server/backend/newsAlerts.go | 2 +- server/backend/rpcserver.go | 2 +- server/backend/updateNote.go | 2 +- 6 files changed, 75 insertions(+), 73 deletions(-) diff --git a/server/backend/cafeteriaService.go b/server/backend/cafeteriaService.go index 6fd7bead..b1ae6299 100644 --- a/server/backend/cafeteriaService.go +++ b/server/backend/cafeteriaService.go @@ -41,10 +41,11 @@ const ( // The parameter limit defines how many actual ratings should be returned. // The optional parameters from and to can define an interval in which the queried ratings have been stored. // If these aren't specified, the newest ratings will be returned as the default -func (s *CampusServer) GetCafeteriaRatings(_ context.Context, input *pb.GetCanteenRatingsRequest) (*pb.GetCanteenRatingsReply, error) { +func (s *CampusServer) GetCafeteriaRatings(ctx context.Context, input *pb.GetCanteenRatingsRequest) (*pb.GetCanteenRatingsReply, error) { var result model.CafeteriaRatingAverage //get the average rating for this specific cafeteria - cafeteriaId := getIDForCafeteriaName(input.CanteenId, s.db) - res := s.db.Model(&model.CafeteriaRatingAverage{}). + tx := s.db.WithContext(ctx) + cafeteriaId := getIDForCafeteriaName(input.CanteenId, tx) + res := tx.Model(&model.CafeteriaRatingAverage{}). Where("cafeteriaId = ?", cafeteriaId). First(&result) @@ -54,8 +55,8 @@ func (s *CampusServer) GetCafeteriaRatings(_ context.Context, input *pb.GetCante } if res.RowsAffected > 0 { - ratings := queryLastCafeteriaRatingsWithLimit(input, cafeteriaId, s) - cafeteriaTags := queryTags(s.db, cafeteriaId, -1, CAFETERIA) + ratings := queryLastCafeteriaRatingsWithLimit(input, cafeteriaId, tx) + cafeteriaTags := queryTags(cafeteriaId, -1, CAFETERIA, tx) return &pb.GetCanteenRatingsReply{ Avg: float64(result.Average), @@ -77,7 +78,7 @@ func (s *CampusServer) GetCafeteriaRatings(_ context.Context, input *pb.GetCante // queryLastCafeteriaRatingsWithLimit // Queries the actual ratings for a cafeteria and attaches the tag ratings which belong to the ratings -func queryLastCafeteriaRatingsWithLimit(input *pb.GetCanteenRatingsRequest, cafeteriaID int32, s *CampusServer) []*pb.SingleRatingReply { +func queryLastCafeteriaRatingsWithLimit(input *pb.GetCanteenRatingsRequest, cafeteriaID int32, tx *gorm.DB) []*pb.SingleRatingReply { var ratings []model.CafeteriaRating var err error @@ -101,13 +102,13 @@ func queryLastCafeteriaRatingsWithLimit(input *pb.GetCanteenRatingsRequest, cafe } else { to = input.To.AsTime() } - err = s.db.Model(&model.CafeteriaRating{}). + err = tx.Model(&model.CafeteriaRating{}). Where("cafeteriaID = ? AND timestamp < ? AND timestamp > ?", cafeteriaID, to, from). Order("timestamp desc, cafeteriaRating desc"). Limit(limit). Find(&ratings).Error } else { - err = s.db.Model(&model.CafeteriaRating{}). + err = tx.Model(&model.CafeteriaRating{}). Where("cafeteriaID = ?", cafeteriaID). Order("timestamp desc, cafeteriaRating desc"). Limit(limit). @@ -122,7 +123,7 @@ func queryLastCafeteriaRatingsWithLimit(input *pb.GetCanteenRatingsRequest, cafe for i, v := range ratings { - tagRatings := queryTagRatingsOverviewForRating(s, v.CafeteriaRating, CAFETERIA) + tagRatings := queryTagRatingsOverviewForRating(v.CafeteriaRating, CAFETERIA, tx) ratingResults[i] = &pb.SingleRatingReply{ Points: v.Points, Comment: v.Comment, @@ -145,12 +146,13 @@ func queryLastCafeteriaRatingsWithLimit(input *pb.GetCanteenRatingsRequest, cafe // The parameter limit defines how many actual ratings should be returned. // The optional parameters from and to can define a interval in which the queried ratings have been stored. // If these aren't specified, the newest ratings will be returned as the default -func (s *CampusServer) GetDishRatings(_ context.Context, input *pb.GetDishRatingsRequest) (*pb.GetDishRatingsReply, error) { +func (s *CampusServer) GetDishRatings(ctx context.Context, input *pb.GetDishRatingsRequest) (*pb.GetDishRatingsReply, error) { var result model.DishRatingAverage //get the average rating for this specific dish - cafeteriaID := getIDForCafeteriaName(input.CanteenId, s.db) - dishID := getIDForDishName(input.Dish, cafeteriaID, s.db) + tx := s.db.WithContext(ctx) + cafeteriaID := getIDForCafeteriaName(input.CanteenId, tx) + dishID := getIDForDishName(input.Dish, cafeteriaID, tx) - err := s.db.Model(&model.DishRatingAverage{}). + err := tx.Model(&model.DishRatingAverage{}). Where("cafeteriaID = ? AND dishID = ?", cafeteriaID, dishID). First(&result) @@ -161,9 +163,9 @@ func (s *CampusServer) GetDishRatings(_ context.Context, input *pb.GetDishRating } if err.RowsAffected > 0 { - ratings := queryLastDishRatingsWithLimit(input, cafeteriaID, dishID, s) - dishTags := queryTags(s.db, cafeteriaID, dishID, DISH) - nameTags := queryTags(s.db, cafeteriaID, dishID, NAME) + ratings := queryLastDishRatingsWithLimit(input, cafeteriaID, dishID, tx) + dishTags := queryTags(cafeteriaID, dishID, DISH, tx) + nameTags := queryTags(cafeteriaID, dishID, NAME, tx) return &pb.GetDishRatingsReply{ Avg: float64(result.Average), @@ -187,7 +189,7 @@ func (s *CampusServer) GetDishRatings(_ context.Context, input *pb.GetDishRating // queryLastDishRatingsWithLimit // Queries the actual ratings for a dish in a cafeteria and attaches the tag ratings which belong to the ratings -func queryLastDishRatingsWithLimit(input *pb.GetDishRatingsRequest, cafeteriaID int32, dishID int32, s *CampusServer) []*pb.SingleRatingReply { +func queryLastDishRatingsWithLimit(input *pb.GetDishRatingsRequest, cafeteriaID int32, dishID int32, tx *gorm.DB) []*pb.SingleRatingReply { var ratings []model.DishRating var err error var limit = int(input.Limit) @@ -210,13 +212,13 @@ func queryLastDishRatingsWithLimit(input *pb.GetDishRatingsRequest, cafeteriaID to = input.To.AsTime() } - err = s.db.Model(&model.DishRating{}). + err = tx.Model(&model.DishRating{}). Where("cafeteriaID = ? AND dishID = ? AND timestamp < ? AND timestamp > ?", cafeteriaID, dishID, to, from). Order("timestamp desc, dishRating desc"). Limit(limit). Find(&ratings).Error } else { - err = s.db.Model(&model.DishRating{}). + err = tx.Model(&model.DishRating{}). Where("cafeteriaID = ? AND dishID = ?", cafeteriaID, dishID). Order("timestamp desc, dishRating desc"). Limit(limit). @@ -233,7 +235,7 @@ func queryLastDishRatingsWithLimit(input *pb.GetDishRatingsRequest, cafeteriaID ratingResults[i] = &pb.SingleRatingReply{ Points: v.Points, Comment: v.Comment, - RatingTags: queryTagRatingsOverviewForRating(s, v.DishRating, DISH), + RatingTags: queryTagRatingsOverviewForRating(v.DishRating, DISH, tx), Image: getImageToBytes(v.Image), Visited: timestamppb.New(v.Timestamp), } @@ -282,25 +284,25 @@ type queryRatingTag struct { // queryTags // Queries the average ratings for either cafeteriaRatingTags, dishRatingTags or NameTags. // Since the db only stores IDs in the results, the tags must be joined to retrieve their names form the rating_options tables. -func queryTags(db *gorm.DB, cafeteriaID int32, dishID int32, ratingType modelType) []*pb.RatingTagResult { +func queryTags(cafeteriaID int32, dishID int32, ratingType modelType, tx *gorm.DB) []*pb.RatingTagResult { var results []queryRatingTag var err error if ratingType == DISH { - err = db.Table("dish_rating_tag_option options"). + err = tx.Table("dish_rating_tag_option options"). Joins("JOIN dish_rating_tag_average results ON options.dishRatingTagOption = results.tagID"). Select("options.dishRatingTagOption as tagId, results.average as avg, "+ "results.min as min, results.max as max, results.std as std"). Where("results.cafeteriaID = ? AND results.dishID = ?", cafeteriaID, dishID). Scan(&results).Error } else if ratingType == CAFETERIA { - err = db.Table("cafeteria_rating_tag_option options"). + err = tx.Table("cafeteria_rating_tag_option options"). Joins("JOIN cafeteria_rating_tag_average results ON options.cafeteriaRatingTagOption = results.tagID"). Select("options.cafeteriaRatingTagOption as tagId, results.average as avg, "+ "results.min as min, results.max as max, results.std as std"). Where("results.cafeteriaID = ?", cafeteriaID). Scan(&results).Error } else { //Query for name tags - err = db.Table("dish_to_dish_name_tag mapping"). + err = tx.Table("dish_to_dish_name_tag mapping"). Where("mapping.dishID = ?", dishID). Select("mapping.nameTagID as tag"). Joins("JOIN dish_name_tag_average results ON mapping.nameTagID = results.tagID"). @@ -331,16 +333,16 @@ func queryTags(db *gorm.DB, cafeteriaID int32, dishID int32, ratingType modelTyp // queryTagRatingOverviewForRating // Query all rating tags which belong to a specific rating given with an ID and return it as TagRatingOverviews -func queryTagRatingsOverviewForRating(s *CampusServer, dishID int32, ratingType modelType) []*pb.RatingTagNewRequest { +func queryTagRatingsOverviewForRating(dishID int32, ratingType modelType, tx *gorm.DB) []*pb.RatingTagNewRequest { var results []*pb.RatingTagNewRequest var err error if ratingType == DISH { - err = s.db.Table("dish_rating_tag_option options"). + err = tx.Table("dish_rating_tag_option options"). Joins("JOIN dish_rating_tag rating ON options.dishRatingTagOption = rating.tagID"). Select("dishRatingTagOption as tagId, points, parentRating"). Find(&results, "parentRating = ?", dishID).Error } else { - err = s.db.Table("cafeteria_rating_tag_option options"). + err = tx.Table("cafeteria_rating_tag_option options"). Joins("JOIN cafeteria_rating_tag rating ON options.cafeteriaRatingTagOption = rating.tagID"). Select("cafeteriaRatingTagOption as tagId, points, correspondingRating"). Find(&results, "correspondingRating = ?", dishID).Error @@ -357,8 +359,9 @@ func queryTagRatingsOverviewForRating(s *CampusServer, dishID int32, ratingType // If one of the parameters is invalid, an error will be returned. Otherwise, the rating will be saved. // All rating tags which were given with the new rating are stored if they are valid tags, if at least one tag was // invalid, an error is returned, all valid ratings tags will be stored nevertheless. Either the german or the english name can be returned to successfully store tags -func (s *CampusServer) NewCanteenRating(_ context.Context, input *pb.NewCanteenRatingRequest) (*pb.NewCanteenRatingReply, error) { - cafeteriaID, errorRes := inputSanitizationForNewRatingElements(input.Points, input.Comment, input.CanteenId, s) +func (s *CampusServer) NewCanteenRating(ctx context.Context, input *pb.NewCanteenRatingRequest) (*pb.NewCanteenRatingReply, error) { + tx := s.db.WithContext(ctx) + cafeteriaID, errorRes := inputSanitizationForNewRatingElements(input.Points, input.Comment, input.CanteenId, tx) if errorRes != nil { return nil, errorRes } @@ -371,13 +374,12 @@ func (s *CampusServer) NewCanteenRating(_ context.Context, input *pb.NewCanteenR Timestamp: time.Now(), Image: resPath, } - - if err := s.db.Model(&model.CafeteriaRating{}).Create(&rating).Error; err != nil { + if err := tx.Model(&model.CafeteriaRating{}).Create(&rating).Error; err != nil { log.WithError(err).Error("Error occurred while creating the new cafeteria rating.") return nil, status.Error(codes.InvalidArgument, "Error while creating new cafeteria rating. Rating has not been saved.") } - if err := storeRatingTags(s, rating.CafeteriaRating, input.RatingTags, CAFETERIA); err != nil { + if err := storeRatingTags(rating.CafeteriaRating, input.RatingTags, CAFETERIA, tx); err != nil { return &pb.NewCanteenRatingReply{}, err } return &pb.NewCanteenRatingReply{}, nil @@ -442,15 +444,15 @@ func storeImage(path string, i []byte) (string, error) { // The ratingNumber will be saved for each corresponding DishNameTag. // All rating tags which were given with the new rating are stored if they are valid tags, if at least one tag was // invalid, an error is returned, all valid ratings tags will be stored nevertheless. Either the german or the english name can be returned to successfully store tags -func (s *CampusServer) NewDishRating(_ context.Context, input *pb.NewDishRatingRequest) (*pb.NewDishRatingReply, error) { - - cafeteriaID, errorRes := inputSanitizationForNewRatingElements(input.Points, input.Comment, input.CanteenId, s) +func (s *CampusServer) NewDishRating(ctx context.Context, input *pb.NewDishRatingRequest) (*pb.NewDishRatingReply, error) { + tx := s.db.WithContext(ctx) + cafeteriaID, errorRes := inputSanitizationForNewRatingElements(input.Points, input.Comment, input.CanteenId, tx) if errorRes != nil { return nil, errorRes } var dish *model.Dish - errDish := s.db.Model(&model.Dish{}). //Dish must exist in the given mensa + errDish := tx.Model(&model.Dish{}). //Dish must exist in the given mensa Where("name LIKE ? AND cafeteriaID = ?", input.Dish, cafeteriaID). First(&dish).Error if errDish != nil || dish == nil { @@ -469,14 +471,14 @@ func (s *CampusServer) NewDishRating(_ context.Context, input *pb.NewDishRatingR Image: resPath, } - if err := s.db.Model(&model.DishRating{}).Create(&rating).Error; err != nil { + if err := tx.Model(&model.DishRating{}).Create(&rating).Error; err != nil { log.WithError(err).Error("while creating a new dish rating.") return nil, status.Error(codes.Internal, "Error while creating the new rating in the database. Rating has not been saved.") } - assignDishNameTag(s, rating, dish.Dish) + assignDishNameTag(rating, dish.Dish, tx) - if err := storeRatingTags(s, rating.DishRating, input.RatingTags, DISH); err != nil { + if err := storeRatingTags(rating.DishRating, input.RatingTags, DISH, tx); err != nil { return &pb.NewDishRatingReply{}, err } return &pb.NewDishRatingReply{}, nil @@ -484,9 +486,9 @@ func (s *CampusServer) NewDishRating(_ context.Context, input *pb.NewDishRatingR // assignDishNameTag // Query all name tags for this specific dish and generate the DishNameTag Ratings ffor each name tag -func assignDishNameTag(s *CampusServer, rating model.DishRating, dishID int32) { +func assignDishNameTag(rating model.DishRating, dishID int32, tx *gorm.DB) { var result []int - err := s.db.Model(&model.DishToDishNameTag{}). + err := tx.Model(&model.DishToDishNameTag{}). Where("dishID = ? ", dishID). Select("nameTagID"). Scan(&result).Error @@ -494,7 +496,7 @@ func assignDishNameTag(s *CampusServer, rating model.DishRating, dishID int32) { log.WithError(err).Error("while loading the dishID for the given name.") } else { for _, tagID := range result { - err := s.db.Model(&model.DishNameTag{}).Create(&model.DishNameTag{ + err := tx.Model(&model.DishNameTag{}).Create(&model.DishNameTag{ CorrespondingRating: rating.DishRating, Points: rating.Points, TagNameID: tagID, @@ -508,7 +510,7 @@ func assignDishNameTag(s *CampusServer, rating model.DishRating, dishID int32) { // inputSanitizationForNewRatingElements Checks parameters of the new rating for all cafeteria and dish ratings. // Additionally, queries the cafeteria ID, since it checks whether the cafeteria actually exists. -func inputSanitizationForNewRatingElements(rating int32, comment string, cafeteriaName string, s *CampusServer) (int32, error) { +func inputSanitizationForNewRatingElements(rating int32, comment string, cafeteriaName string, tx *gorm.DB) (int32, error) { if rating > 5 || rating < 0 { return -1, status.Error(codes.InvalidArgument, "Rating must be a positive number not larger than 10. Rating has not been saved.") } @@ -522,7 +524,7 @@ func inputSanitizationForNewRatingElements(rating int32, comment string, cafeter } var result *model.Cafeteria - res := s.db.Model(&model.Cafeteria{}). + res := tx.Model(&model.Cafeteria{}). Where("name LIKE ?", cafeteriaName). First(&result) if errors.Is(res.Error, gorm.ErrRecordNotFound) || res.RowsAffected == 0 { @@ -536,27 +538,27 @@ func inputSanitizationForNewRatingElements(rating int32, comment string, cafeter // storeRatingTags // Checks whether the rating-tag name is a valid option and if so, // it will be saved with a reference to the rating -func storeRatingTags(s *CampusServer, parentRatingID int32, tags []*pb.RatingTag, tagType modelType) error { +func storeRatingTags(parentRatingID int32, tags []*pb.RatingTag, tagType modelType, tx *gorm.DB) error { var errorOccurred = "" var warningOccurred = "" if len(tags) > 0 { usedTagIds := make(map[int]int) - insertModel := getModelStoreTag(tagType, s.db) + insertModel := getModelStoreTag(tagType, tx) for _, currentTag := range tags { var err error var count int64 if tagType == DISH { - err = s.db.Model(&model.DishRatingTagOption{}). + err = tx.Model(&model.DishRatingTagOption{}). Where("dishRatingTagOption LIKE ?", currentTag.TagId). Count(&count).Error } else { - err = s.db.Model(&model.CafeteriaRatingTagOption{}). + err = tx.Model(&model.CafeteriaRatingTagOption{}). Where("cafeteriaRatingTagOption LIKE ?", currentTag.TagId). Count(&count).Error } - if err == gorm.ErrRecordNotFound || count == 0 { + if errors.Is(err, gorm.ErrRecordNotFound) || count == 0 { fields := log.Fields{ "tagid": currentTag.TagId, "count": count, @@ -597,17 +599,17 @@ func storeRatingTags(s *CampusServer, parentRatingID int32, tags []*pb.RatingTag } -func getModelStoreTag(tagType modelType, db *gorm.DB) *gorm.DB { +func getModelStoreTag(tagType modelType, tx *gorm.DB) *gorm.DB { if tagType == DISH { - return db.Model(&model.DishRatingTag{}) + return tx.Model(&model.DishRatingTag{}) } else { - return db.Model(&model.CafeteriaRatingTag{}) + return tx.Model(&model.CafeteriaRatingTag{}) } } -func getIDForCafeteriaName(name string, db *gorm.DB) int32 { +func getIDForCafeteriaName(name string, tx *gorm.DB) int32 { var result int32 = -1 - err := db.Model(&model.Cafeteria{}). + err := tx.Model(&model.Cafeteria{}). Where("name LIKE ?", name). Select("cafeteria"). Scan(&result).Error @@ -618,9 +620,9 @@ func getIDForCafeteriaName(name string, db *gorm.DB) int32 { return result } -func getIDForDishName(name string, cafeteriaID int32, db *gorm.DB) int32 { +func getIDForDishName(name string, cafeteriaID int32, tx *gorm.DB) int32 { var result int32 = -1 - err := db.Model(&model.Dish{}). + err := tx.Model(&model.Dish{}). Where("name LIKE ? AND cafeteriaID = ?", name, cafeteriaID). Select("dish"). Scan(&result).Error @@ -634,10 +636,10 @@ func getIDForDishName(name string, cafeteriaID int32, db *gorm.DB) int32 { // GetAvailableDishTags RPC Endpoint // Returns all valid Tags to quickly rate dishes in english and german with the corresponding Id -func (s *CampusServer) GetAvailableDishTags(_ context.Context, _ *pb.GetAvailableDishTagsRequest) (*pb.GetAvailableDishTagsReply, error) { +func (s *CampusServer) GetAvailableDishTags(ctx context.Context, _ *pb.GetAvailableDishTagsRequest) (*pb.GetAvailableDishTagsReply, error) { var result []*pb.TagsOverview var requestStatus error = nil - err := s.db.Model(&model.DishRatingTagOption{}).Select("DE as de, EN as en, dishRatingTagOption as TagId").Find(&result).Error + err := s.db.WithContext(ctx).Model(&model.DishRatingTagOption{}).Select("DE as de, EN as en, dishRatingTagOption as TagId").Find(&result).Error if err != nil { log.WithError(err).Error("while loading Cafeterias from database.") requestStatus = status.Error(codes.Internal, "Available dish tags could not be loaded from the database.") @@ -650,10 +652,10 @@ func (s *CampusServer) GetAvailableDishTags(_ context.Context, _ *pb.GetAvailabl // GetNameTags RPC Endpoint // Returns all valid Tags to quickly rate dishes in english and german with the corresponding Id -func (s *CampusServer) GetNameTags(_ context.Context, _ *pb.GetNameTagsRequest) (*pb.GetNameTagsReply, error) { +func (s *CampusServer) GetNameTags(ctx context.Context, _ *pb.GetNameTagsRequest) (*pb.GetNameTagsReply, error) { var result []*pb.TagsOverview var requestStatus error = nil - err := s.db.Model(&model.DishNameTagOption{}).Select("DE as de, EN as en, dishNameTagOption as TagId").Find(&result).Error + err := s.db.WithContext(ctx).Model(&model.DishNameTagOption{}).Select("DE as de, EN as en, dishNameTagOption as TagId").Find(&result).Error if err != nil { log.WithError(err).Error("while loading available Name Tags from database.") requestStatus = status.Error(codes.Internal, "Available dish tags could not be loaded from the database.") @@ -666,10 +668,10 @@ func (s *CampusServer) GetNameTags(_ context.Context, _ *pb.GetNameTagsRequest) // GetAvailableCafeteriaTags RPC Endpoint // Returns all valid Tags to quickly rate dishes in english and german -func (s *CampusServer) GetAvailableCafeteriaTags(_ context.Context, _ *pb.GetAvailableCanteenTagsRequest) (*pb.GetAvailableCanteenTagsReply, error) { +func (s *CampusServer) GetAvailableCafeteriaTags(ctx context.Context, _ *pb.GetAvailableCanteenTagsRequest) (*pb.GetAvailableCanteenTagsReply, error) { var result []*pb.TagsOverview var requestStatus error = nil - err := s.db.Model(&model.CafeteriaRatingTagOption{}).Select("DE as de, EN as en, cafeteriaRatingsTagOption as TagId").Find(&result).Error + err := s.db.WithContext(ctx).Model(&model.CafeteriaRatingTagOption{}).Select("DE as de, EN as en, cafeteriaRatingsTagOption as TagId").Find(&result).Error if err != nil { log.WithError(err).Error("while loading Cafeterias from database.") requestStatus = status.Error(codes.Internal, "Available cafeteria tags could not be loaded from the database.") @@ -682,10 +684,10 @@ func (s *CampusServer) GetAvailableCafeteriaTags(_ context.Context, _ *pb.GetAva // GetCafeterias RPC endpoint // Returns all cafeterias with meta information which are available in the eat-api -func (s *CampusServer) GetCafeterias(_ context.Context, _ *pb.GetCanteensRequest) (*pb.GetCanteensReply, error) { +func (s *CampusServer) GetCafeterias(ctx context.Context, _ *pb.GetCanteensRequest) (*pb.GetCanteensReply, error) { var result []*pb.Canteen var requestStatus error = nil - err := s.db.Model(&model.Cafeteria{}).Select("cafeteria as id,address,latitude,longitude").Scan(&result).Error + err := s.db.WithContext(ctx).Model(&model.Cafeteria{}).Select("cafeteria as id,address,latitude,longitude").Scan(&result).Error if err != nil { log.WithError(err).Error("while loading Cafeterias from database.") requestStatus = status.Error(codes.Internal, "Cafeterias could not be loaded from the database.") @@ -696,7 +698,7 @@ func (s *CampusServer) GetCafeterias(_ context.Context, _ *pb.GetCanteensRequest }, requestStatus } -func (s *CampusServer) GetDishes(_ context.Context, request *pb.GetDishesRequest) (*pb.GetDishesReply, error) { +func (s *CampusServer) GetDishes(ctx context.Context, request *pb.GetDishesRequest) (*pb.GetDishesReply, error) { if request.Year < 2022 { return &pb.GetDishesReply{}, status.Error(codes.Internal, "Years must be larger or equal to 2022 ") // currently, no previous values have been added } @@ -709,7 +711,7 @@ func (s *CampusServer) GetDishes(_ context.Context, request *pb.GetDishesRequest var requestStatus error = nil var results []string - err := s.db.Table("dishes_of_the_week weekly"). + err := s.db.WithContext(ctx).Table("dishes_of_the_week weekly"). Where("weekly.day = ? AND weekly.week = ? and weekly.year = ?", request.Day, request.Week, request.Year). Select("weekly.dishID"). Joins("JOIN dish d ON d.dish = weekly.dishID"). diff --git a/server/backend/canteenHeadCount.go b/server/backend/canteenHeadCount.go index 589b2b7e..5aa1c8fc 100644 --- a/server/backend/canteenHeadCount.go +++ b/server/backend/canteenHeadCount.go @@ -12,9 +12,9 @@ import ( ) // GetCanteenHeadCount RPC Endpoint -func (s *CampusServer) GetCanteenHeadCount(_ context.Context, input *pb.GetCanteenHeadCountRequest) (*pb.GetCanteenHeadCountReply, error) { +func (s *CampusServer) GetCanteenHeadCount(ctx context.Context, input *pb.GetCanteenHeadCountRequest) (*pb.GetCanteenHeadCountReply, error) { data := model.CanteenHeadCount{Count: 0, MaxCount: 0, Percent: -1} // Initialize with an empty (not found) value - err := s.db.Model(&model.CanteenHeadCount{}).Where(model.CanteenHeadCount{CanteenId: input.CanteenId}).FirstOrInit(&data).Error + err := s.db.WithContext(ctx).Model(&model.CanteenHeadCount{}).Where(model.CanteenHeadCount{CanteenId: input.CanteenId}).FirstOrInit(&data).Error if err != nil && !errors.Is(err, gorm.ErrRecordNotFound) { log.WithError(err).Error("while querying the canteen head count for: ", input.CanteenId) return nil, errors.New("failed to query head count") diff --git a/server/backend/news.go b/server/backend/news.go index a2038aeb..013b3fba 100644 --- a/server/backend/news.go +++ b/server/backend/news.go @@ -19,7 +19,7 @@ func (s *CampusServer) GetNewsSources(ctx context.Context, _ *pb.GetNewsSourcesR } var sources []model.NewsSource - if err := s.db.Joins("Files").Find(&sources).Error; err != nil { + if err := s.db.WithContext(ctx).Joins("Files").Find(&sources).Error; err != nil { log.WithError(err).Error("could not find newsSources") return nil, status.Error(codes.Internal, "could not GetNewsSources") } @@ -42,7 +42,7 @@ func (s *CampusServer) GetNews(ctx context.Context, req *pb.GetNewsRequest) (*pb } var newsEntries []model.News - tx := s.db.Joins("Files") + tx := s.db.WithContext(ctx).Joins("Files") if req.NewsSource != 0 { tx = tx.Where("src = ?", req.NewsSource) } diff --git a/server/backend/newsAlerts.go b/server/backend/newsAlerts.go index cbb61354..6189b256 100644 --- a/server/backend/newsAlerts.go +++ b/server/backend/newsAlerts.go @@ -19,7 +19,7 @@ func (s *CampusServer) GetTopNews(ctx context.Context, _ *pb.GetTopNewsRequest) } var res *model.NewsAlert - err := s.db.Joins("Files").Where("NOW() between `from` and `to`").First(&res).Error + err := s.db.WithContext(ctx).Joins("Files").Where("NOW() between `from` and `to`").First(&res).Error if errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.Error(codes.NotFound, "no current active top news") } else if err != nil { diff --git a/server/backend/rpcserver.go b/server/backend/rpcserver.go index 1a29439e..c5989bcc 100644 --- a/server/backend/rpcserver.go +++ b/server/backend/rpcserver.go @@ -80,7 +80,7 @@ func (s *CampusServer) SearchRooms(ctx context.Context, req *pb.SearchRoomsReque Campus string Name string } - err := s.db.Raw("SELECT r.*, a.campus, a.name "+ + err := s.db.WithContext(ctx).Raw("SELECT r.*, a.campus, a.name "+ "FROM roomfinder_rooms r "+ "LEFT JOIN roomfinder_building2area a ON a.building_nr = r.building_nr "+ "WHERE MATCH(room_code, info, address) AGAINST(?)", req.Query).Scan(&res).Error diff --git a/server/backend/updateNote.go b/server/backend/updateNote.go index a9f48164..70d1fbb7 100644 --- a/server/backend/updateNote.go +++ b/server/backend/updateNote.go @@ -19,7 +19,7 @@ func (s *CampusServer) GetUpdateNote(ctx context.Context, req *pb.GetUpdateNoteR } res := model.UpdateNote{VersionCode: req.Version} - if err := s.db.First(&res).Error; errors.Is(err, gorm.ErrRecordNotFound) { + if err := s.db.WithContext(ctx).First(&res).Error; errors.Is(err, gorm.ErrRecordNotFound) { return nil, status.Error(codes.NotFound, "No update note found") } else if err != nil { log.WithField("VersionCode", req.Version).WithError(err).Error("Failed to get update note") From f034ba4ef86eaa34dfba4fb0b4b4e594c3d67457 Mon Sep 17 00:00:00 2001 From: Frank Elsinga Date: Tue, 19 Sep 2023 18:18:47 +0200 Subject: [PATCH 2/2] fuxed the clients mod --- client/go.mod | 2 +- client/go.sum | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/client/go.mod b/client/go.mod index a3f7c8bc..3d345397 100644 --- a/client/go.mod +++ b/client/go.mod @@ -3,7 +3,7 @@ module github.com/TUM-Dev/Campus-Backend/client go 1.21 require ( - github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919151227-4e173519f39f + github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919155641-f895a75987e0 github.com/sirupsen/logrus v1.9.3 google.golang.org/grpc v1.58.1 ) diff --git a/client/go.sum b/client/go.sum index f04371f9..ba3cbef0 100644 --- a/client/go.sum +++ b/client/go.sum @@ -1,5 +1,5 @@ -github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919151227-4e173519f39f h1:+SvWYtUOg+L0DiuFvxwmdo4B48Dllk5M1oRG0Zsfyuw= -github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919151227-4e173519f39f/go.mod h1:fjoLL3rbdY6wTRJIksekT2p3OUp5ocFfXjB/avV/TVI= +github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919155641-f895a75987e0 h1:rZqUJmywWU9aV9Bk/IYKIYN76+nYcATD2q+pFVBYQN4= +github.com/TUM-Dev/Campus-Backend/server v0.0.0-20230919155641-f895a75987e0/go.mod h1:fjoLL3rbdY6wTRJIksekT2p3OUp5ocFfXjB/avV/TVI= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=