Skip to content

armgit / lyftr

Public Imported from GitHub
0

Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.

refactor(stores): migrate exercises to ExerciseStore

Cawlumm7ebf4dd2ed1b
diff --git a/backend/controllers/exercises.go b/backend/controllers/exercises.go
index 4bba013..4023ffa 100644
--- a/backend/controllers/exercises.go
+++ b/backend/controllers/exercises.go
@@ -1,57 +1,30 @@
package controllers
import (
- "encoding/json"
+ "database/sql"
"strconv"
- "github.com/Cawlumm/lyftr-backend/db"
- "github.com/Cawlumm/lyftr-backend/models"
- "github.com/Cawlumm/lyftr-backend/seed"
+ "github.com/Cawlumm/lyftr-backend/middleware"
+ "github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
)
func (h *Handler) ListExercises(c *gin.Context) {
- query := `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_url
- FROM exercises WHERE 1=1`
- args := []any{}
-
- if q := c.Query("q"); q != "" {
- query += " AND name LIKE ?"
- args = append(args, "%"+q+"%")
- }
- if mg := c.Query("muscle_group"); mg != "" {
- query += " AND muscle_group = ?"
- args = append(args, mg)
- }
- if cat := c.Query("category"); cat != "" {
- query += " AND category = ?"
- args = append(args, cat)
- }
- if eq := c.Query("equipment"); eq != "" {
- query += " AND equipment = ?"
- args = append(args, eq)
+ f := stores.ExerciseFilter{
+ Query: c.Query("q"),
+ MuscleGroup: c.Query("muscle_group"),
+ Category: c.Query("category"),
+ Equipment: c.Query("equipment"),
+ Limit: 100,
}
-
- limit := 100
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 2000 {
- limit = l
+ f.Limit = l
}
- query += " ORDER BY name LIMIT ?"
- args = append(args, limit)
-
- rows, err := db.DB.Query(query, args...)
- if err != nil {
- utils.InternalError(c)
+ exercises, err := h.s.Exercise.List(f)
+ if utils.DBError(c, err) {
return
}
- defer rows.Close()
-
- exercises := []models.Exercise{}
- for rows.Next() {
- e := scanExercise(rows)
- exercises = append(exercises, e)
- }
utils.OK(c, exercises)
}
@@ -61,136 +34,82 @@ func (h *Handler) GetExercise(c *gin.Context) {
utils.BadRequest(c, "invalid exercise id")
return
}
-
- row := db.DB.QueryRow(
- `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_url
- FROM exercises WHERE id = ?`, id,
- )
- e := scanExercise(row)
- if e.ID == 0 {
+ e, err := h.s.Exercise.Get(id)
+ if err == sql.ErrNoRows {
utils.NotFound(c, "exercise not found")
return
}
+ if utils.DBError(c, err) {
+ return
+ }
utils.OK(c, e)
}
func (h *Handler) GetExercisePRs(c *gin.Context) {
- userID := c.GetInt64("user_id")
+ uid := middleware.UserID(c)
exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
utils.BadRequest(c, "invalid exercise id")
return
}
-
- row := db.DB.QueryRow(`
- SELECT s.weight, s.reps, w.started_at, w.id
- FROM sets s
- JOIN workout_exercises we ON we.id = s.workout_exercise_id
- JOIN workouts w ON w.id = we.workout_id
- WHERE w.user_id = ? AND we.exercise_id = ? AND s.is_warmup = 0 AND s.weight > 0
- ORDER BY s.weight DESC, s.reps DESC
- LIMIT 1
- `, userID, exerciseID)
-
- var weight float64
- var reps int
- var date string
- var workoutID int64
- if err := row.Scan(&weight, &reps, &date, &workoutID); err != nil {
+ pr, err := h.s.Workout.PRForExercise(uid, exerciseID)
+ if err == sql.ErrNoRows {
utils.OK(c, nil)
return
}
-
- estimated1RM := weight * (1 + float64(reps)/30.0)
+ if utils.DBError(c, err) {
+ return
+ }
utils.OK(c, gin.H{
- "weight": weight,
- "reps": reps,
- "estimated_1rm": estimated1RM,
- "date": date,
- "workout_id": workoutID,
+ "weight": pr.Weight,
+ "reps": pr.Reps,
+ "estimated_1rm": pr.Weight * (1 + float64(pr.Reps)/30.0),
+ "date": pr.Date,
+ "workout_id": pr.WorkoutID,
})
}
func (h *Handler) GetExerciseHistory(c *gin.Context) {
- userID := c.GetInt64("user_id")
+ uid := middleware.UserID(c)
exerciseID, err := strconv.ParseInt(c.Param("id"), 10, 64)
if err != nil {
utils.BadRequest(c, "invalid exercise id")
return
}
-
limit := 20
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 100 {
limit = l
}
-
- rows, err := db.DB.Query(`
- SELECT w.started_at, MAX(s.weight), SUM(s.reps * s.weight), COUNT(s.id)
- FROM sets s
- JOIN workout_exercises we ON we.id = s.workout_exercise_id
- JOIN workouts w ON w.id = we.workout_id
- WHERE w.user_id = ? AND we.exercise_id = ? AND s.is_warmup = 0
- GROUP BY w.id
- ORDER BY w.started_at DESC
- LIMIT ?
- `, userID, exerciseID, limit)
- if err != nil {
- utils.InternalError(c)
+ history, err := h.s.Workout.HistoryForExercise(uid, exerciseID, limit)
+ if utils.DBError(c, err) {
return
}
- defer rows.Close()
-
- type point struct {
- Date string `json:"date"`
- MaxWeight float64 `json:"max_weight"`
- TotalVolume float64 `json:"total_volume"`
- SetsCount int `json:"sets_count"`
- }
- history := []point{}
- for rows.Next() {
- var p point
- rows.Scan(&p.Date, &p.MaxWeight, &p.TotalVolume, &p.SetsCount)
- history = append(history, p)
- }
utils.OK(c, history)
}
// SyncExercises is an admin-only endpoint to re-pull from ExerciseDB.
func (h *Handler) SyncExercises(c *gin.Context) {
- if err := seed.SyncExercises(db.DB); err != nil {
+ if err := h.s.Exercise.Sync(); err != nil {
utils.BadRequest(c, err.Error())
return
}
- var count int
- db.DB.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&count)
+ count, err := h.s.Exercise.Count()
+ if utils.DBError(c, err) {
+ return
+ }
utils.OK(c, gin.H{"synced": true, "total": count})
}
// ExerciseSeedStatus returns exercise count and whether seeding is running.
func (h *Handler) ExerciseSeedStatus(c *gin.Context) {
- utils.OK(c, seed.GetSeedStatus(db.DB))
+ utils.OK(c, h.s.Exercise.SeedStatus())
}
// ResetExercises wipes the exercises table and triggers a fresh seed in background.
func (h *Handler) ResetExercises(c *gin.Context) {
- if err := seed.WipeAndReseed(db.DB); err != nil {
+ if err := h.s.Exercise.Reset(); err != nil {
utils.BadRequest(c, err.Error())
return
}
utils.OK(c, gin.H{"reset": true, "message": "exercises wiped, re-seeding in background"})
}
-
-type scanner interface {
- Scan(dest ...any) error
-}
-
-func scanExercise(row scanner) models.Exercise {
- var e models.Exercise
- var secondaryRaw string
- row.Scan(&e.ID, &e.Name, &e.MuscleGroup, &secondaryRaw, &e.Category, &e.Equipment, &e.Description, &e.ImageURL)
- json.Unmarshal([]byte(secondaryRaw), &e.SecondaryMuscles)
- if e.SecondaryMuscles == nil {
- e.SecondaryMuscles = []string{}
- }
- return e
-}
diff --git a/backend/stores/exercise.go b/backend/stores/exercise.go
index 1480138..2923817 100644
--- a/backend/stores/exercise.go
+++ b/backend/stores/exercise.go
@@ -1,8 +1,91 @@
package stores
-import "database/sql"
+import (
+ "database/sql"
+ "encoding/json"
-// ExerciseStore owns all SQL for the exercise entity.
+ "github.com/Cawlumm/lyftr-backend/models"
+ "github.com/Cawlumm/lyftr-backend/seed"
+)
+
+// ExerciseStore owns all SQL for the (global, read-only) exercises catalog, and
+// wraps the seed subsystem for the admin sync/reset endpoints.
type ExerciseStore struct{ db *sql.DB }
func NewExerciseStore(db *sql.DB) *ExerciseStore { return &ExerciseStore{db: db} }
+
+// ExerciseFilter holds the optional list filters (empty string = no filter).
+type ExerciseFilter struct {
+ Query, MuscleGroup, Category, Equipment string
+ Limit int
+}
+
+const exerciseSelect = `SELECT id, name, muscle_group, secondary_muscles, category, equipment, description, image_url FROM exercises`
+
+type scanner interface{ Scan(dest ...any) error }
+
+func scanExercise(row scanner) models.Exercise {
+ var e models.Exercise
+ var secondaryRaw string
+ row.Scan(&e.ID, &e.Name, &e.MuscleGroup, &secondaryRaw, &e.Category, &e.Equipment, &e.Description, &e.ImageURL)
+ json.Unmarshal([]byte(secondaryRaw), &e.SecondaryMuscles)
+ if e.SecondaryMuscles == nil {
+ e.SecondaryMuscles = []string{}
+ }
+ return e
+}
+
+func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {
+ q := exerciseSelect + ` WHERE 1=1`
+ args := []any{}
+ if f.Query != "" {
+ q += " AND name LIKE ?"
+ args = append(args, "%"+f.Query+"%")
+ }
+ if f.MuscleGroup != "" {
+ q += " AND muscle_group = ?"
+ args = append(args, f.MuscleGroup)
+ }
+ if f.Category != "" {
+ q += " AND category = ?"
+ args = append(args, f.Category)
+ }
+ if f.Equipment != "" {
+ q += " AND equipment = ?"
+ args = append(args, f.Equipment)
+ }
+ q += " ORDER BY name LIMIT ?"
+ args = append(args, f.Limit)
+
+ rows, err := s.db.Query(q, args...)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ exercises := []models.Exercise{}
+ for rows.Next() {
+ exercises = append(exercises, scanExercise(rows))
+ }
+ return exercises, rows.Err()
+}
+
+// Get returns one exercise, or sql.ErrNoRows if not found.
+func (s *ExerciseStore) Get(id int64) (models.Exercise, error) {
+ e := scanExercise(s.db.QueryRow(exerciseSelect+` WHERE id = ?`, id))
+ if e.ID == 0 {
+ return models.Exercise{}, sql.ErrNoRows
+ }
+ return e, nil
+}
+
+func (s *ExerciseStore) Count() (int, error) {
+ var n int
+ err := s.db.QueryRow(`SELECT COUNT(*) FROM exercises`).Scan(&n)
+ return n, err
+}
+
+// Sync / SeedStatus / Reset delegate to the seed subsystem (which owns the
+// ExerciseDB fetch + the concurrency guard) so the controller stays SQL-free.
+func (s *ExerciseStore) Sync() error { return seed.SyncExercises(s.db) }
+func (s *ExerciseStore) SeedStatus() seed.SeedStatus { return seed.GetSeedStatus(s.db) }
+func (s *ExerciseStore) Reset() error { return seed.WipeAndReseed(s.db) }
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 43a434d..2dc8aa2 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -17,3 +17,62 @@ func (s *WorkoutStore) CountOn(uid int64, date string) (int, error) {
).Scan(&n)
return n, err
}
+
+// ExercisePR is the best single set for an exercise (heaviest, then most reps).
+type ExercisePR struct {
+ Weight float64
+ Reps int
+ Date string
+ WorkoutID int64
+}
+
+// ExerciseHistoryPoint is a per-workout rollup for an exercise's progress chart.
+type ExerciseHistoryPoint struct {
+ Date string `json:"date"`
+ MaxWeight float64 `json:"max_weight"`
+ TotalVolume float64 `json:"total_volume"`
+ SetsCount int `json:"sets_count"`
+}
+
+// PRForExercise returns the user's PR set for an exercise, or sql.ErrNoRows if
+// they have no qualifying (non-warmup, weighted) set. Reads workout tables — this
+// is workout-derived analytics keyed by exercise, so it lives on WorkoutStore.
+func (s *WorkoutStore) PRForExercise(uid, exerciseID int64) (ExercisePR, error) {
+ var pr ExercisePR
+ err := s.db.QueryRow(`
+ SELECT s.weight, s.reps, w.started_at, w.id
+ FROM sets s
+ JOIN workout_exercises we ON we.id = s.workout_exercise_id
+ JOIN workouts w ON w.id = we.workout_id
+ WHERE w.user_id = ? AND we.exercise_id = ? AND s.is_warmup = 0 AND s.weight > 0
+ ORDER BY s.weight DESC, s.reps DESC
+ LIMIT 1
+ `, uid, exerciseID).Scan(&pr.Weight, &pr.Reps, &pr.Date, &pr.WorkoutID)
+ return pr, err
+}
+
+func (s *WorkoutStore) HistoryForExercise(uid, exerciseID int64, limit int) ([]ExerciseHistoryPoint, error) {
+ rows, err := s.db.Query(`
+ SELECT w.started_at, MAX(s.weight), SUM(s.reps * s.weight), COUNT(s.id)
+ FROM sets s
+ JOIN workout_exercises we ON we.id = s.workout_exercise_id
+ JOIN workouts w ON w.id = we.workout_id
+ WHERE w.user_id = ? AND we.exercise_id = ? AND s.is_warmup = 0
+ GROUP BY w.id
+ ORDER BY w.started_at DESC
+ LIMIT ?
+ `, uid, exerciseID, limit)
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ history := []ExerciseHistoryPoint{}
+ for rows.Next() {
+ var p ExerciseHistoryPoint
+ if err := rows.Scan(&p.Date, &p.MaxWeight, &p.TotalVolume, &p.SetsCount); err != nil {
+ return nil, err
+ }
+ history = append(history, p)
+ }
+ return history, rows.Err()
+}