Improve score retrieval

This commit is contained in:
nemunaire 2022-02-28 17:45:30 +01:00
parent d77e6e2eac
commit 567e170cfd
2 changed files with 16 additions and 4 deletions

2
db.go
View File

@ -157,7 +157,7 @@ CREATE TABLE IF NOT EXISTS student_corrected(
return err
}
if _, err := db.Exec(`
CREATE VIEW IF NOT EXISTS student_scores AS SELECT U.id_user, id_survey, Q.id_question, MAX(R.score) as score FROM survey_quests Q CROSS JOIN users U LEFT JOIN survey_responses R ON Q.id_question = R.id_question AND R.id_user = U.id_user GROUP BY Q.id_question, U.id_user;
CREATE VIEW IF NOT EXISTS student_scores AS SELECT T.id_user, T.id_survey, Q.id_question, MAX(R.score) AS score FROM (SELECT DISTINCT R.id_user, S.id_survey FROM survey_responses R INNER JOIN survey_quests Q ON R.id_question = Q.id_question INNER JOIN surveys S ON Q.id_survey = S.id_survey) T LEFT OUTER JOIN survey_quests Q ON T.id_survey = Q.id_survey LEFT OUTER JOIN survey_responses R ON R.id_user = T.id_user AND Q.id_question = R.id_question GROUP BY id_user, id_survey, id_question;
`); err != nil {
return err
}

View File

@ -12,6 +12,10 @@ import (
"github.com/julienschmidt/httprouter"
)
var (
_score_cache = map[int64]map[int64]*float64{}
)
func init() {
router.GET("/api/surveys", apiAuthHandler(
func(u *User, _ httprouter.Params, _ []byte) HTTPResponse {
@ -182,9 +186,17 @@ func NewSurvey(title string, promo uint, group string, shown bool, startAvailabi
}
func (s Survey) GetScore(u *User) (score *float64, err error) {
err = DBQueryRow("SELECT SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? AND id_user=?", s.Id, u.Id).Scan(&score)
if score != nil {
*score = *score / 5.0
if _, ok := _score_cache[u.Id]; !ok {
_score_cache[u.Id] = map[int64]*float64{}
}
if v, ok := _score_cache[u.Id][s.Id]; ok {
score = v
} else {
err = DBQueryRow("SELECT SUM(score)/COUNT(*) FROM student_scores WHERE id_survey=? AND id_user=?", s.Id, u.Id).Scan(&score)
if score != nil {
*score = *score / 5.0
}
_score_cache[u.Id][s.Id] = score
}
return
}