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 workouts to WorkoutStore (folds #36 cursor fix)

Cawlumm5bc9a541f7fa
diff --git a/backend/controllers/concurrency_test.go b/backend/controllers/concurrency_test.go
new file mode 100644
index 0000000..a03b987
--- /dev/null
+++ b/backend/controllers/concurrency_test.go
@@ -0,0 +1,74 @@
+package controllers
+
+import (
+ "fmt"
+ "sync"
+ "testing"
+ "time"
+
+ "github.com/Cawlumm/lyftr-backend/db"
+)
+
+// Regression test for #30: list handlers used to run nested queries while a
+// parent rows cursor was still open, so each request needed multiple pool
+// connections at once. With the pool capped at N, N concurrent requests
+// deadlocked the pool permanently. The fix (in WorkoutStore.loadExercises) scans
+// parents fully and closes the cursor before loading children, so one connection
+// per request suffices.
+func TestListWorkoutsConcurrentDoesNotExhaustPool(t *testing.T) {
+ setupTestDB(t)
+ uid := createTestUser(t)
+ exID := createTestExercise(t)
+
+ // Two workouts with exercises and sets so the nested loaders actually run.
+ for w := 0; w < 2; w++ {
+ res, err := db.DB.Exec(
+ `INSERT INTO workouts (user_id, name) VALUES (?, ?)`, uid, fmt.Sprintf("Workout %d", w),
+ )
+ if err != nil {
+ t.Fatalf("insert workout: %v", err)
+ }
+ wid, _ := res.LastInsertId()
+ weRes, err := db.DB.Exec(
+ `INSERT INTO workout_exercises (workout_id, exercise_id, order_index) VALUES (?, ?, 0)`, wid, exID,
+ )
+ if err != nil {
+ t.Fatalf("insert workout_exercise: %v", err)
+ }
+ weid, _ := weRes.LastInsertId()
+ if _, err := db.DB.Exec(
+ `INSERT INTO sets (workout_exercise_id, set_number, reps, weight) VALUES (?, 1, 5, 135)`, weid,
+ ); err != nil {
+ t.Fatalf("insert set: %v", err)
+ }
+ }
+
+ // Small pool + more concurrent requests than connections: the old nested
+ // cursor pattern deadlocks here; the fixed code must finish promptly.
+ db.DB.SetMaxOpenConns(2)
+ const concurrency = 6
+
+ done := make(chan struct{})
+ go func() {
+ var wg sync.WaitGroup
+ for i := 0; i < concurrency; i++ {
+ wg.Add(1)
+ go func() {
+ defer wg.Done()
+ c, w := newContext(uid, "GET", "/workouts", nil)
+ th.ListWorkouts(c)
+ if w.Code != 200 {
+ t.Errorf("ListWorkouts returned %d", w.Code)
+ }
+ }()
+ }
+ wg.Wait()
+ close(done)
+ }()
+
+ select {
+ case <-done:
+ case <-time.After(10 * time.Second):
+ t.Fatal("concurrent ListWorkouts deadlocked the connection pool (#30 regression)")
+ }
+}
diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.go
index 81b8470..3bee08b 100644
--- a/backend/controllers/workouts.go
+++ b/backend/controllers/workouts.go
@@ -3,56 +3,28 @@ package controllers
import (
"database/sql"
"strconv"
- "strings"
"time"
- "github.com/Cawlumm/lyftr-backend/db"
"github.com/Cawlumm/lyftr-backend/middleware"
"github.com/Cawlumm/lyftr-backend/models"
+ "github.com/Cawlumm/lyftr-backend/stores"
"github.com/Cawlumm/lyftr-backend/utils"
"github.com/gin-gonic/gin"
)
func (h *Handler) ListWorkouts(c *gin.Context) {
uid := middleware.UserID(c)
- limit := 20
- offset := 0
+ f := stores.WorkoutFilter{Limit: 20, Query: c.Query("q")}
if l, err := strconv.Atoi(c.Query("limit")); err == nil && l > 0 && l <= 100 {
- limit = l
+ f.Limit = l
}
if o, err := strconv.Atoi(c.Query("offset")); err == nil && o >= 0 {
- offset = o
+ f.Offset = o
}
- q := c.Query("q")
-
- var rows *sql.Rows
- var err error
- if q != "" {
- rows, err = db.DB.Query(
- `SELECT id, user_id, name, notes, duration, started_at, created_at
- FROM workouts WHERE user_id = ? AND LOWER(name) LIKE ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
- uid, "%"+strings.ToLower(q)+"%", limit, offset,
- )
- } else {
- rows, err = db.DB.Query(
- `SELECT id, user_id, name, notes, duration, started_at, created_at
- FROM workouts WHERE user_id = ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
- uid, limit, offset,
- )
- }
- if err != nil {
- utils.InternalError(c)
+ workouts, err := h.s.Workout.List(uid, f)
+ if utils.DBError(c, err) {
return
}
- defer rows.Close()
-
- workouts := []models.Workout{}
- for rows.Next() {
- var w models.Workout
- rows.Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)
- w.Exercises = loadWorkoutExercises(w.ID)
- workouts = append(workouts, w)
- }
utils.OK(c, workouts)
}
@@ -63,22 +35,14 @@ func (h *Handler) GetWorkout(c *gin.Context) {
utils.BadRequest(c, "invalid workout id")
return
}
-
- var w models.Workout
- err = db.DB.QueryRow(
- `SELECT id, user_id, name, notes, duration, started_at, created_at
- FROM workouts WHERE id = ? AND user_id = ?`, wid, uid,
- ).Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)
+ w, err := h.s.Workout.Get(uid, wid)
if err == sql.ErrNoRows {
utils.NotFound(c, "workout not found")
return
}
- if err != nil {
- utils.InternalError(c)
+ if utils.DBError(c, err) {
return
}
-
- w.Exercises = loadWorkoutExercises(wid)
utils.OK(c, w)
}
@@ -93,69 +57,13 @@ func (h *Handler) CreateWorkout(c *gin.Context) {
utils.ValidationError(c, err)
return
}
-
if req.StartedAt.IsZero() {
req.StartedAt = time.Now()
}
-
- tx, err := db.DB.Begin()
- if err != nil {
- utils.InternalError(c)
- return
- }
- defer tx.Rollback()
-
- res, err := tx.Exec(
- `INSERT INTO workouts (user_id, name, notes, duration, started_at) VALUES (?, ?, ?, ?, ?)`,
- uid, req.Name, req.Notes, req.Duration, req.StartedAt,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
- wid, err := res.LastInsertId()
- if err != nil {
- utils.InternalError(c)
- return
- }
-
- for i, ex := range req.Exercises {
- exRes, err := tx.Exec(
- `INSERT INTO workout_exercises (workout_id, exercise_id, order_index, notes) VALUES (?, ?, ?, ?)`,
- wid, ex.ExerciseID, i, ex.Notes,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
- weid, err := exRes.LastInsertId()
- if err != nil {
- utils.InternalError(c)
- return
- }
- for j, s := range ex.Sets {
- _, err := tx.Exec(
- `INSERT INTO sets (workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- weid, j+1, s.Reps, s.Weight, s.Duration, s.Distance, s.RPE, s.IsWarmup,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
- }
- }
-
- if err := tx.Commit(); err != nil {
- utils.InternalError(c)
+ w, err := h.s.Workout.Create(uid, req)
+ if utils.DBError(c, err) {
return
}
-
- var w models.Workout
- db.DB.QueryRow(
- `SELECT id, user_id, name, notes, duration, started_at, created_at FROM workouts WHERE id = ?`, wid,
- ).Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)
- w.Exercises = loadWorkoutExercises(wid)
utils.Created(c, w)
}
@@ -166,7 +74,6 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
utils.BadRequest(c, "invalid workout id")
return
}
-
var req models.CreateWorkoutRequest
if err := c.ShouldBindJSON(&req); err != nil {
utils.BadRequest(c, err.Error())
@@ -176,79 +83,14 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {
utils.ValidationError(c, err)
return
}
-
- var existing models.Workout
- err = db.DB.QueryRow(
- `SELECT id, user_id FROM workouts WHERE id = ? AND user_id = ?`, wid, uid,
- ).Scan(&existing.ID, &existing.UserID)
+ w, err := h.s.Workout.Update(uid, wid, req)
if err == sql.ErrNoRows {
utils.NotFound(c, "workout not found")
return
}
- if err != nil {
- utils.InternalError(c)
+ if utils.DBError(c, err) {
return
}
-
- tx, err := db.DB.Begin()
- if err != nil {
- utils.InternalError(c)
- return
- }
- defer tx.Rollback()
-
- _, err = tx.Exec(
- `UPDATE workouts SET name = ?, notes = ?, duration = ?, started_at = ? WHERE id = ?`,
- req.Name, req.Notes, req.Duration, req.StartedAt, wid,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
-
- _, err = tx.Exec(`DELETE FROM workout_exercises WHERE workout_id = ?`, wid)
- if err != nil {
- utils.InternalError(c)
- return
- }
-
- for i, ex := range req.Exercises {
- exRes, err := tx.Exec(
- `INSERT INTO workout_exercises (workout_id, exercise_id, order_index, notes) VALUES (?, ?, ?, ?)`,
- wid, ex.ExerciseID, i, ex.Notes,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
- weid, err := exRes.LastInsertId()
- if err != nil {
- utils.InternalError(c)
- return
- }
- for j, s := range ex.Sets {
- _, err := tx.Exec(
- `INSERT INTO sets (workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup)
- VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
- weid, j+1, s.Reps, s.Weight, s.Duration, s.Distance, s.RPE, s.IsWarmup,
- )
- if err != nil {
- utils.InternalError(c)
- return
- }
- }
- }
-
- if err := tx.Commit(); err != nil {
- utils.InternalError(c)
- return
- }
-
- var w models.Workout
- db.DB.QueryRow(
- `SELECT id, user_id, name, notes, duration, started_at, created_at FROM workouts WHERE id = ?`, wid,
- ).Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)
- w.Exercises = loadWorkoutExercises(wid)
utils.OK(c, w)
}
@@ -259,65 +101,13 @@ func (h *Handler) DeleteWorkout(c *gin.Context) {
utils.BadRequest(c, "invalid workout id")
return
}
-
- res, err := db.DB.Exec(`DELETE FROM workouts WHERE id = ? AND user_id = ?`, wid, uid)
- if err != nil {
- utils.InternalError(c)
+ n, err := h.s.Workout.Delete(uid, wid)
+ if utils.DBError(c, err) {
return
}
- n, _ := res.RowsAffected()
if n == 0 {
utils.NotFound(c, "workout not found")
return
}
utils.OK(c, gin.H{"deleted": true})
}
-
-func loadWorkoutExercises(workoutID int64) []models.WorkoutExercise {
- rows, err := db.DB.Query(
- `SELECT we.id, we.workout_id, we.exercise_id, we.order_index, we.notes,
- e.name, e.muscle_group, e.category, e.equipment, e.image_url
- FROM workout_exercises we
- JOIN exercises e ON e.id = we.exercise_id
- WHERE we.workout_id = ? ORDER BY we.order_index`,
- workoutID,
- )
- if err != nil {
- return nil
- }
- defer rows.Close()
-
- var exercises []models.WorkoutExercise
- for rows.Next() {
- var we models.WorkoutExercise
- rows.Scan(
- &we.ID, &we.WorkoutID, &we.ExerciseID, &we.OrderIndex, &we.Notes,
- &we.Exercise.Name, &we.Exercise.MuscleGroup, &we.Exercise.Category,
- &we.Exercise.Equipment, &we.Exercise.ImageURL,
- )
- we.Exercise.ID = we.ExerciseID
- we.Sets = loadSets(we.ID)
- exercises = append(exercises, we)
- }
- return exercises
-}
-
-func loadSets(workoutExerciseID int64) []models.Set {
- rows, err := db.DB.Query(
- `SELECT id, workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup
- FROM sets WHERE workout_exercise_id = ? ORDER BY set_number`,
- workoutExerciseID,
- )
- if err != nil {
- return nil
- }
- defer rows.Close()
-
- var sets []models.Set
- for rows.Next() {
- var s models.Set
- rows.Scan(&s.ID, &s.WorkoutExerciseID, &s.SetNumber, &s.Reps, &s.Weight, &s.Duration, &s.Distance, &s.RPE, &s.IsWarmup)
- sets = append(sets, s)
- }
- return sets
-}
diff --git a/backend/stores/workout.go b/backend/stores/workout.go
index 2dc8aa2..1adb71a 100644
--- a/backend/stores/workout.go
+++ b/backend/stores/workout.go
@@ -1,12 +1,264 @@
package stores
-import "database/sql"
+import (
+ "database/sql"
+ "strings"
-// WorkoutStore owns all SQL for the workout entity.
+ "github.com/Cawlumm/lyftr-backend/models"
+)
+
+// WorkoutStore owns all SQL for workouts, workout_exercises and sets, plus the
+// workout-derived exercise analytics (PRs/history/daily count).
type WorkoutStore struct{ db *sql.DB }
func NewWorkoutStore(db *sql.DB) *WorkoutStore { return &WorkoutStore{db: db} }
+// WorkoutFilter holds list paging + optional name search.
+type WorkoutFilter struct {
+ Limit, Offset int
+ Query string
+}
+
+const workoutCols = `id, user_id, name, notes, duration, started_at, created_at`
+
+func scanWorkout(row interface{ Scan(...any) error }, w *models.Workout) error {
+ return row.Scan(&w.ID, &w.UserID, &w.Name, &w.Notes, &w.Duration, &w.StartedAt, &w.CreatedAt)
+}
+
+func (s *WorkoutStore) List(uid int64, f WorkoutFilter) ([]models.Workout, error) {
+ var rows *sql.Rows
+ var err error
+ if f.Query != "" {
+ rows, err = s.db.Query(
+ `SELECT `+workoutCols+` FROM workouts WHERE user_id = ? AND LOWER(name) LIKE ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
+ uid, "%"+strings.ToLower(f.Query)+"%", f.Limit, f.Offset,
+ )
+ } else {
+ rows, err = s.db.Query(
+ `SELECT `+workoutCols+` FROM workouts WHERE user_id = ? ORDER BY started_at DESC LIMIT ? OFFSET ?`,
+ uid, f.Limit, f.Offset,
+ )
+ }
+ if err != nil {
+ return nil, err
+ }
+ workouts := []models.Workout{}
+ for rows.Next() {
+ var w models.Workout
+ if err := scanWorkout(rows, &w); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ workouts = append(workouts, w)
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ rows.Close() // close the parent cursor BEFORE loading children (#36: avoid holding 2 pool connections per request)
+
+ for i := range workouts {
+ ex, err := s.loadExercises(workouts[i].ID)
+ if err != nil {
+ return nil, err
+ }
+ workouts[i].Exercises = ex
+ }
+ return workouts, nil
+}
+
+// Get returns a user-owned workout with its exercises/sets, or sql.ErrNoRows.
+func (s *WorkoutStore) Get(uid, id int64) (models.Workout, error) {
+ var w models.Workout
+ if err := scanWorkout(
+ s.db.QueryRow(`SELECT `+workoutCols+` FROM workouts WHERE id = ? AND user_id = ?`, id, uid), &w,
+ ); err != nil {
+ return models.Workout{}, err
+ }
+ ex, err := s.loadExercises(id)
+ if err != nil {
+ return models.Workout{}, err
+ }
+ w.Exercises = ex
+ return w, nil
+}
+
+// get re-reads by id (no user scope) — used after a user-scoped write.
+func (s *WorkoutStore) get(id int64) (models.Workout, error) {
+ var w models.Workout
+ if err := scanWorkout(s.db.QueryRow(`SELECT `+workoutCols+` FROM workouts WHERE id = ?`, id), &w); err != nil {
+ return models.Workout{}, err
+ }
+ ex, err := s.loadExercises(id)
+ if err != nil {
+ return models.Workout{}, err
+ }
+ w.Exercises = ex
+ return w, nil
+}
+
+func (s *WorkoutStore) Create(uid int64, req models.CreateWorkoutRequest) (models.Workout, error) {
+ tx, err := s.db.Begin()
+ if err != nil {
+ return models.Workout{}, err
+ }
+ defer tx.Rollback()
+
+ res, err := tx.Exec(
+ `INSERT INTO workouts (user_id, name, notes, duration, started_at) VALUES (?, ?, ?, ?, ?)`,
+ uid, req.Name, req.Notes, req.Duration, req.StartedAt,
+ )
+ if err != nil {
+ return models.Workout{}, err
+ }
+ wid, err := res.LastInsertId()
+ if err != nil {
+ return models.Workout{}, err
+ }
+ if err := insertWorkoutExercises(tx, wid, req.Exercises); err != nil {
+ return models.Workout{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return models.Workout{}, err
+ }
+ return s.get(wid)
+}
+
+// Update replaces a user-owned workout and its children in one tx. sql.ErrNoRows
+// if the workout isn't theirs (nothing is mutated).
+func (s *WorkoutStore) Update(uid, id int64, req models.CreateWorkoutRequest) (models.Workout, error) {
+ var ownedID int64
+ if err := s.db.QueryRow(`SELECT id FROM workouts WHERE id = ? AND user_id = ?`, id, uid).Scan(&ownedID); err != nil {
+ return models.Workout{}, err // ErrNoRows = not theirs
+ }
+
+ tx, err := s.db.Begin()
+ if err != nil {
+ return models.Workout{}, err
+ }
+ defer tx.Rollback()
+
+ if _, err := tx.Exec(
+ `UPDATE workouts SET name = ?, notes = ?, duration = ?, started_at = ? WHERE id = ?`,
+ req.Name, req.Notes, req.Duration, req.StartedAt, id,
+ ); err != nil {
+ return models.Workout{}, err
+ }
+ // Children replaced wholesale; sets cascade-delete with their workout_exercise.
+ if _, err := tx.Exec(`DELETE FROM workout_exercises WHERE workout_id = ?`, id); err != nil {
+ return models.Workout{}, err
+ }
+ if err := insertWorkoutExercises(tx, id, req.Exercises); err != nil {
+ return models.Workout{}, err
+ }
+ if err := tx.Commit(); err != nil {
+ return models.Workout{}, err
+ }
+ return s.get(id)
+}
+
+func (s *WorkoutStore) Delete(uid, id int64) (int64, error) {
+ res, err := s.db.Exec(`DELETE FROM workouts WHERE id = ? AND user_id = ?`, id, uid)
+ if err != nil {
+ return 0, err
+ }
+ n, _ := res.RowsAffected()
+ return n, nil
+}
+
+// insertWorkoutExercises writes the exercises + their sets for a workout within tx.
+func insertWorkoutExercises(tx *sql.Tx, wid int64, exercises []models.CreateWorkoutExerciseReq) error {
+ for i, ex := range exercises {
+ exRes, err := tx.Exec(
+ `INSERT INTO workout_exercises (workout_id, exercise_id, order_index, notes) VALUES (?, ?, ?, ?)`,
+ wid, ex.ExerciseID, i, ex.Notes,
+ )
+ if err != nil {
+ return err
+ }
+ weid, err := exRes.LastInsertId()
+ if err != nil {
+ return err
+ }
+ for j, st := range ex.Sets {
+ if _, err := tx.Exec(
+ `INSERT INTO sets (workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup)
+ VALUES (?, ?, ?, ?, ?, ?, ?, ?)`,
+ weid, j+1, st.Reps, st.Weight, st.Duration, st.Distance, st.RPE, st.IsWarmup,
+ ); err != nil {
+ return err
+ }
+ }
+ }
+ return nil
+}
+
+// loadExercises loads a workout's exercises (JOIN exercises for display) then
+// their sets. Scans + closes the parent cursor fully BEFORE the per-exercise set
+// queries (#36) so a request never holds two pool connections at once.
+func (s *WorkoutStore) loadExercises(workoutID int64) ([]models.WorkoutExercise, error) {
+ rows, err := s.db.Query(
+ `SELECT we.id, we.workout_id, we.exercise_id, we.order_index, we.notes,
+ e.name, e.muscle_group, e.category, e.equipment, e.image_url
+ FROM workout_exercises we
+ JOIN exercises e ON e.id = we.exercise_id
+ WHERE we.workout_id = ? ORDER BY we.order_index`,
+ workoutID,
+ )
+ if err != nil {
+ return nil, err
+ }
+ var exercises []models.WorkoutExercise
+ for rows.Next() {
+ var we models.WorkoutExercise
+ if err := rows.Scan(
+ &we.ID, &we.WorkoutID, &we.ExerciseID, &we.OrderIndex, &we.Notes,
+ &we.Exercise.Name, &we.Exercise.MuscleGroup, &we.Exercise.Category,
+ &we.Exercise.Equipment, &we.Exercise.ImageURL,
+ ); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ we.Exercise.ID = we.ExerciseID
+ exercises = append(exercises, we)
+ }
+ if err := rows.Err(); err != nil {
+ rows.Close()
+ return nil, err
+ }
+ rows.Close()
+
+ for i := range exercises {
+ sets, err := s.loadSets(exercises[i].ID)
+ if err != nil {
+ return nil, err
+ }
+ exercises[i].Sets = sets
+ }
+ return exercises, nil
+}
+
+func (s *WorkoutStore) loadSets(workoutExerciseID int64) ([]models.Set, error) {
+ rows, err := s.db.Query(
+ `SELECT id, workout_exercise_id, set_number, reps, weight, duration, distance, rpe, is_warmup
+ FROM sets WHERE workout_exercise_id = ? ORDER BY set_number`,
+ workoutExerciseID,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ var sets []models.Set
+ for rows.Next() {
+ var st models.Set
+ if err := rows.Scan(&st.ID, &st.WorkoutExerciseID, &st.SetNumber, &st.Reps, &st.Weight, &st.Duration, &st.Distance, &st.RPE, &st.IsWarmup); err != nil {
+ return nil, err
+ }
+ sets = append(sets, st)
+ }
+ return sets, rows.Err()
+}
+
// CountOn returns how many workouts the user started on the given calendar day
// (YYYY-MM-DD). Used by the food daily-stats view (cross-entity composition).
func (s *WorkoutStore) CountOn(uid int64, date string) (int, error) {