Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

playerHandler| N+1を部分的に解消 #16

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
50 changes: 29 additions & 21 deletions go/isuports.go
Original file line number Diff line number Diff line change
Expand Up @@ -1306,36 +1306,44 @@ func playerHandler(c echo.Context) error {
// player_scoreを読んでいるときに更新が走ると不整合が起こるのでロックを取得する
fl, err := flockByTenantID(v.tenantID)
if err != nil {
fl.Close()
return fmt.Errorf("error flockByTenantID: %w", err)
}
defer fl.Close()
pss := make([]PlayerScoreRow, 0, len(cs))
for _, c := range cs {
ps := PlayerScoreRow{}
if err := tenantDB.GetContext(
ctx,
&ps,
// 最後にCSVに登場したスコアを採用する = row_numが一番大きいもの
"SELECT * FROM player_score WHERE tenant_id = ? AND competition_id = ? AND player_id = ? ORDER BY row_num DESC LIMIT 1",
v.tenantID,
c.ID,
p.ID,
); err != nil {
// 行がない = スコアが記録されてない
if errors.Is(err, sql.ErrNoRows) {
continue
}
return fmt.Errorf("error Select player_score: tenantID=%d, competitionID=%s, playerID=%s, %w", v.tenantID, c.ID, p.ID, err)
}
pss = append(pss, ps)
query := `
SELECT s.* FROM player_score AS s JOIN
(SELECT MAX(row_num) AS num, competition_id FROM player_score WHERE tenant_id = ? AND player_id = ? GROUP BY competition_id) AS t
ON s.competition_id = t.competition_id AND s.row_num = t.num WHERE tenant_id = ? AND player_id = ?
`
err = tenantDB.SelectContext(ctx, &pss, query, v.tenantID, p.ID, v.tenantID, p.ID)
if err != nil && !errors.Is(err, sql.ErrNoRows) {
fl.Close()
return fmt.Errorf("error Select player_score: %w", err)
}
fl.Close()

pssCompetitionIDs := make([]interface{}, 0, len(cs))
for _, ps := range pss {
pssCompetitionIDs = append(pssCompetitionIDs, ps.CompetitionID)
}

var comps []CompetitionRow
if err := tenantDB.SelectContext(ctx, &comps, fmt.Sprintf("SELECT * FROM competition WHERE id IN (%s?)", strings.Repeat("?,", len(pssCompetitionIDs)-1)), pssCompetitionIDs...); err != nil {
return fmt.Errorf("error Select competition: %w", err)
}

compsByID := make(map[string]CompetitionRow)
for _, comp := range comps {
compsByID[comp.ID] = comp
}

psds := make([]PlayerScoreDetail, 0, len(pss))
for _, ps := range pss {
comp, err := retrieveCompetition(ctx, tenantDB, ps.CompetitionID)
if err != nil {
comp, ok := compsByID[ps.CompetitionID]
if !ok {
return fmt.Errorf("error retrieveCompetition: %w", err)
}

psds = append(psds, PlayerScoreDetail{
CompetitionTitle: comp.Title,
Score: ps.Score,
Expand Down