Improve score retrieval
This commit is contained in:
parent
11c49bcb34
commit
1e17c7bb40
2
db.go
2
db.go
@ -156,7 +156,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
|
||||
}
|
||||
|
18
surveys.go
18
surveys.go
@ -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
|
||||
}
|
||||
|
Reference in New Issue
Block a user