func updateTagCount()

in internal/migrations/v13.go [173:255]


func updateTagCount(ctx context.Context, x *xorm.Engine) error {
	tagRelList := make([]entity.TagRel, 0)
	err := x.Context(ctx).Find(&tagRelList, &entity.TagRel{})
	if err != nil {
		return fmt.Errorf("get tag rel failed: %w", err)
	}
	questionIDs := make([]string, 0)
	questionsAvailableMap := make(map[string]bool)
	questionsHideMap := make(map[string]bool)
	for _, item := range tagRelList {
		questionIDs = append(questionIDs, item.ObjectID)
		questionsAvailableMap[item.ObjectID] = false
		questionsHideMap[item.ObjectID] = false
	}
	questionList := make([]QuestionV13, 0)
	err = x.Context(ctx).In("id", questionIDs).And(builder.Lt{"question.status": entity.QuestionStatusDeleted}).Find(&questionList, &QuestionV13{})
	if err != nil {
		return fmt.Errorf("get questions failed: %w", err)
	}
	for _, question := range questionList {
		_, ok := questionsAvailableMap[question.ID]
		if ok {
			questionsAvailableMap[question.ID] = true
			if question.Show == entity.QuestionHide {
				questionsHideMap[question.ID] = true
			}
		}
	}

	for id, ok := range questionsHideMap {
		if ok {
			if _, err = x.Context(ctx).Cols("status").Update(&entity.TagRel{Status: entity.TagRelStatusHide}, &entity.TagRel{ObjectID: id}); err != nil {
				log.Errorf("update %+v config failed: %s", id, err)
			}
		}
	}

	for id, ok := range questionsAvailableMap {
		if !ok {
			if _, err = x.Context(ctx).Cols("status").Update(&entity.TagRel{Status: entity.TagRelStatusDeleted}, &entity.TagRel{ObjectID: id}); err != nil {
				log.Errorf("update %+v config failed: %s", id, err)
			}
		}
	}

	//select tag count
	newTagRelList := make([]entity.TagRel, 0)
	err = x.Context(ctx).Find(&newTagRelList, &entity.TagRel{Status: entity.TagRelStatusAvailable})
	if err != nil {
		return fmt.Errorf("get tag rel failed: %w", err)
	}
	tagCountMap := make(map[string]int)
	for _, v := range newTagRelList {
		_, ok := tagCountMap[v.TagID]
		if !ok {
			tagCountMap[v.TagID] = 1
		} else {
			tagCountMap[v.TagID]++
		}
	}
	TagList := make([]entity.Tag, 0)
	err = x.Context(ctx).Find(&TagList, &entity.Tag{})
	if err != nil {
		return fmt.Errorf("get tag  failed: %w", err)
	}
	for _, tag := range TagList {
		_, ok := tagCountMap[tag.ID]
		if ok {
			tag.QuestionCount = tagCountMap[tag.ID]
			if _, err = x.Context(ctx).Update(tag, &entity.Tag{ID: tag.ID}); err != nil {
				log.Errorf("update %+v tag failed: %s", tag.ID, err)
				return fmt.Errorf("update tag failed: %w", err)
			}
		} else {
			tag.QuestionCount = 0
			if _, err = x.Context(ctx).Cols("question_count").Update(tag, &entity.Tag{ID: tag.ID}); err != nil {
				log.Errorf("update %+v tag failed: %s", tag.ID, err)
				return fmt.Errorf("update tag failed: %w", err)
			}
		}
	}
	return nil
}