ranking.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. // Package query contains database queries for the jamtrack application.
  2. package query
  3. import (
  4. "github.com/pocketbase/dbx"
  5. "github.com/pocketbase/pocketbase/core"
  6. )
  7. // SongRank holds the aggregated play statistics for a single song.
  8. type SongRank struct {
  9. ID string `db:"id"`
  10. Artist string `db:"artist"`
  11. Title string `db:"title"`
  12. PlayedCount int `db:"played_count"`
  13. ProposedCount int `db:"proposed_count"`
  14. }
  15. // FetchRanking returns songs ordered by play frequency (played_count desc,
  16. // proposed_count desc). If locationID is non-empty the results are filtered
  17. // to jams at that location.
  18. func FetchRanking(app core.App, locationID string) ([]SongRank, error) {
  19. var rows []SongRank
  20. if locationID != "" {
  21. err := app.DB().
  22. NewQuery(`
  23. SELECT s.id, s.artist, s.title,
  24. COALESCE(SUM(sl.played), 0) AS played_count,
  25. COUNT(sl.id) AS proposed_count
  26. FROM setlist sl
  27. JOIN songs s ON s.id = sl.song
  28. JOIN jams j ON j.id = sl.jam
  29. WHERE j.location = {:location}
  30. GROUP BY s.id
  31. ORDER BY played_count DESC, proposed_count DESC
  32. `).
  33. Bind(dbx.Params{"location": locationID}).
  34. All(&rows)
  35. return rows, err
  36. }
  37. err := app.DB().
  38. NewQuery(`
  39. SELECT s.id, s.artist, s.title,
  40. COALESCE(SUM(sl.played), 0) AS played_count,
  41. COUNT(sl.id) AS proposed_count
  42. FROM setlist sl
  43. JOIN songs s ON s.id = sl.song
  44. GROUP BY s.id
  45. ORDER BY played_count DESC, proposed_count DESC
  46. `).
  47. All(&rows)
  48. return rows, err
  49. }