Self-hosted fitness tracker. Log workouts, track nutrition, and monitor progress. Docker deployment, mobile-friendly.
fix(review): address code-review findings on the store refactor
Cawlumm99961ae11f17
diff --git a/backend/controllers/food.go b/backend/controllers/food.goindex fe3b5ae..6f581f4 100644--- a/backend/controllers/food.go+++ b/backend/controllers/food.go@@ -343,11 +343,11 @@ func (h *Handler) SearchFood(c *gin.Context) {if err != nil {if ctx.Err() == context.DeadlineExceeded {log.Printf("[food/search] OFF timeout after %dms", elapsed.Milliseconds())- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search timed out — try again"})+ utils.ServiceUnavailable(c, "food search timed out — try again")return}log.Printf("[food/search] OFF network error: %v", err)- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "could not reach food database"})+ utils.ServiceUnavailable(c, "could not reach food database")return}@@ -359,11 +359,11 @@ func (h *Handler) SearchFood(c *gin.Context) {returncase status >= 500:log.Printf("[food/search] OFF upstream error: %d", status)- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search temporarily unavailable"})+ utils.ServiceUnavailable(c, "food search temporarily unavailable")returncase status != 200:log.Printf("[food/search] OFF unexpected status: %d", status)- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "food search temporarily unavailable"})+ utils.ServiceUnavailable(c, "food search temporarily unavailable")return}@@ -421,11 +421,11 @@ func (h *Handler) LookupBarcode(c *gin.Context) {if err != nil {if ctx.Err() == context.DeadlineExceeded {log.Printf("[food/barcode] OFF timeout after %dms", elapsed.Milliseconds())- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "barcode lookup timed out — try again"})+ utils.ServiceUnavailable(c, "barcode lookup timed out — try again")return}log.Printf("[food/barcode] OFF network error: %v", err)- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "could not reach food database"})+ utils.ServiceUnavailable(c, "could not reach food database")return}@@ -437,7 +437,7 @@ func (h *Handler) LookupBarcode(c *gin.Context) {returncase status >= 500:log.Printf("[food/barcode] OFF upstream error: %d", status)- c.JSON(http.StatusServiceUnavailable, gin.H{"error": "barcode lookup temporarily unavailable"})+ utils.ServiceUnavailable(c, "barcode lookup temporarily unavailable")return}diff --git a/backend/controllers/programs.go b/backend/controllers/programs.goindex 3595d80..134cabf 100644--- a/backend/controllers/programs.go+++ b/backend/controllers/programs.go@@ -57,6 +57,10 @@ func (h *Handler) CreateProgram(c *gin.Context) {return}p, err := h.s.Program.Create(uid, req)+ if utils.IsForeignKeyViolation(err) {+ utils.BadRequest(c, "one or more exercises do not exist")+ return+ }if utils.DBError(c, err) {return}@@ -84,6 +88,10 @@ func (h *Handler) UpdateProgram(c *gin.Context) {utils.NotFound(c, "program not found")return}+ if utils.IsForeignKeyViolation(err) {+ utils.BadRequest(c, "one or more exercises do not exist")+ return+ }if utils.DBError(c, err) {return}diff --git a/backend/controllers/review_fixes_test.go b/backend/controllers/review_fixes_test.gonew file mode 100644index 0000000..400d95e--- /dev/null+++ b/backend/controllers/review_fixes_test.go@@ -0,0 +1,38 @@+package controllers++import (+ "net/http"+ "testing"+)++// TestGetMe_deletedAccountReturns401 covers the review fix: GetMe used to fall+// through utils.DBError (which ignores sql.ErrNoRows) and return 200 with an+// empty user for a deleted-but-still-authenticated account. It must now 401.+func TestGetMe_deletedAccountReturns401(t *testing.T) {+ setupTestDB(t)+ // No user row with this id exists — account deleted, JWT still valid.+ c, w := newContext(99999, http.MethodGet, "/api/v1/me", nil)+ th.GetMe(c)+ if w.Code != http.StatusUnauthorized {+ t.Fatalf("expected 401 for missing user, got %d (%s)", w.Code, w.Body.String())+ }+}++// TestCreateWorkout_unknownExerciseReturns400 covers the review fix: with foreign+// keys now enforced, a workout referencing a non-existent exercise must surface as+// a clean 400, not a 500 (FK violation) or a silent dangling insert.+func TestCreateWorkout_unknownExerciseReturns400(t *testing.T) {+ setupTestDB(t)+ uid := createTestUser(t)+ body := map[string]any{+ "name": "Test Workout",+ "exercises": []map[string]any{+ {"exercise_id": 99999, "sets": []map[string]any{{"reps": 5, "weight": 100}}},+ },+ }+ c, w := newContext(uid, http.MethodPost, "/api/v1/workouts", body)+ th.CreateWorkout(c)+ if w.Code != http.StatusBadRequest {+ t.Fatalf("expected 400 for unknown exercise_id, got %d (%s)", w.Code, w.Body.String())+ }+}diff --git a/backend/controllers/user.go b/backend/controllers/user.goindex b87579b..0e82bf5 100644--- a/backend/controllers/user.go+++ b/backend/controllers/user.go@@ -12,6 +12,10 @@ import (func (h *Handler) GetMe(c *gin.Context) {uid := middleware.UserID(c)u, err := h.s.User.GetMe(uid)+ if err == sql.ErrNoRows {+ utils.Unauthorized(c, "account no longer exists")+ return+ }if utils.DBError(c, err) {return}diff --git a/backend/controllers/workouts.go b/backend/controllers/workouts.goindex 3bee08b..09316f6 100644--- a/backend/controllers/workouts.go+++ b/backend/controllers/workouts.go@@ -61,6 +61,10 @@ func (h *Handler) CreateWorkout(c *gin.Context) {req.StartedAt = time.Now()}w, err := h.s.Workout.Create(uid, req)+ if utils.IsForeignKeyViolation(err) {+ utils.BadRequest(c, "one or more exercises do not exist")+ return+ }if utils.DBError(c, err) {return}@@ -88,6 +92,10 @@ func (h *Handler) UpdateWorkout(c *gin.Context) {utils.NotFound(c, "workout not found")return}+ if utils.IsForeignKeyViolation(err) {+ utils.BadRequest(c, "one or more exercises do not exist")+ return+ }if utils.DBError(c, err) {return}diff --git a/backend/seed/exercises.go b/backend/seed/exercises.goindex 361b1eb..e088de5 100644--- a/backend/seed/exercises.go+++ b/backend/seed/exercises.go@@ -77,7 +77,12 @@ func WipeAndReseed(db *sql.DB) error {if !seeding.CompareAndSwap(false, true) {return fmt.Errorf("seed already in progress")}- if _, err := db.Exec(`DELETE FROM exercises`); err != nil {+ // Prune only unreferenced exercises: with foreign_keys enforced, deleting an+ // exercise that a saved workout/program references is (correctly) rejected.+ // Referenced rows are refreshed in place by the ON CONFLICT(name) upsert below.+ if _, err := db.Exec(`DELETE FROM exercises+ WHERE id NOT IN (SELECT exercise_id FROM workout_exercises)+ AND id NOT IN (SELECT exercise_id FROM program_exercises)`); err != nil {seeding.Store(false)return fmt.Errorf("wipe failed: %w", err)}diff --git a/backend/stores/exercise.go b/backend/stores/exercise.goindex 2923817..e7a1be0 100644--- a/backend/stores/exercise.go+++ b/backend/stores/exercise.go@@ -24,15 +24,16 @@ const exerciseSelect = `SELECT id, name, muscle_group, secondary_muscles, categotype scanner interface{ Scan(dest ...any) error }-func scanExercise(row scanner) models.Exercise {- var e models.Exercise+func scanExercise(row scanner, e *models.Exercise) error {var secondaryRaw string- row.Scan(&e.ID, &e.Name, &e.MuscleGroup, &secondaryRaw, &e.Category, &e.Equipment, &e.Description, &e.ImageURL)+ if err := row.Scan(&e.ID, &e.Name, &e.MuscleGroup, &secondaryRaw, &e.Category, &e.Equipment, &e.Description, &e.ImageURL); err != nil {+ return err+ }json.Unmarshal([]byte(secondaryRaw), &e.SecondaryMuscles)if e.SecondaryMuscles == nil {e.SecondaryMuscles = []string{}}- return e+ return nil}func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {@@ -64,16 +65,20 @@ func (s *ExerciseStore) List(f ExerciseFilter) ([]models.Exercise, error) {defer rows.Close()exercises := []models.Exercise{}for rows.Next() {- exercises = append(exercises, scanExercise(rows))+ var e models.Exercise+ if err := scanExercise(rows, &e); err != nil {+ return nil, err+ }+ exercises = append(exercises, e)}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+ var e models.Exercise+ if err := scanExercise(s.db.QueryRow(exerciseSelect+` WHERE id = ?`, id), &e); err != nil {+ return models.Exercise{}, err}return e, nil}diff --git a/backend/stores/weight.go b/backend/stores/weight.goindex abcc24f..2fe190d 100644--- a/backend/stores/weight.go+++ b/backend/stores/weight.go@@ -86,21 +86,30 @@ func dayBounds(t time.Time) (time.Time, time.Time) {// entry if present, else insert. req.LoggedAt must already be normalized to UTC.func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest) (models.WeightLog, error) {dayStart, dayEnd := dayBounds(req.LoggedAt)+ // One transaction so the existence check + insert/update is atomic: otherwise+ // the connection is released between the SELECT and the write, and two same-day+ // logs can both miss the row and both insert (duplicate day).+ tx, err := s.db.Begin()+ if err != nil {+ return models.WeightLog{}, err+ }+ defer tx.Rollback()+var id int64- err := s.db.QueryRow(+ err = tx.QueryRow(`SELECT id FROM weight_logs WHERE user_id = ? AND logged_at >= ? AND logged_at < ? ORDER BY id DESC LIMIT 1`,uid, dayStart, dayEnd,).Scan(&id)switch err {case nil:- if _, e := s.db.Exec(+ if _, e := tx.Exec(`UPDATE weight_logs SET weight = ?, notes = ?, logged_at = ? WHERE id = ?`,req.Weight, req.Notes, req.LoggedAt, id,); e != nil {return models.WeightLog{}, e}case sql.ErrNoRows:- res, e := s.db.Exec(+ res, e := tx.Exec(`INSERT INTO weight_logs (user_id, weight, notes, logged_at) VALUES (?, ?, ?, ?)`,uid, req.Weight, req.Notes, req.LoggedAt,)@@ -111,6 +120,9 @@ func (s *WeightStore) UpsertForDay(uid int64, req models.LogWeightRequest) (modedefault:return models.WeightLog{}, err}+ if err := tx.Commit(); err != nil {+ return models.WeightLog{}, err+ }return s.get(id)}@@ -160,28 +172,35 @@ func (s *WeightStore) Stats(uid int64) (WeightStats, error) {if err != nil {return WeightStats{}, err}- return WeightStats{+ stats := WeightStats{Latest: latest.Float64, Starting: oldest.Float64,Min: minW.Float64, Max: maxW.Float64, Avg: avgW.Float64,TotalEntries: count,- Change7d: s.changeOver(uid, 7),- Change30d: s.changeOver(uid, 30),- }, nil+ }+ if stats.Change7d, err = s.changeOver(uid, 7); err != nil {+ return WeightStats{}, err+ }+ if stats.Change30d, err = s.changeOver(uid, 30); err != nil {+ return WeightStats{}, err+ }+ return stats, nil}// changeOver returns latest minus earliest weight within the last `days` days,// or 0 with fewer than two entries in the window.-func (s *WeightStore) changeOver(uid int64, days int) float64 {+func (s *WeightStore) changeOver(uid int64, days int) (float64, error) {cutoff := time.Now().UTC().AddDate(0, 0, -days)var latest, earliest sql.NullFloat64- s.db.QueryRow(+ if err := s.db.QueryRow(`SELECT(SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at DESC, id DESC LIMIT 1),(SELECT weight FROM weight_logs WHERE user_id = ? AND logged_at >= ? ORDER BY logged_at ASC, id ASC LIMIT 1)`,uid, cutoff, uid, cutoff,- ).Scan(&latest, &earliest)+ ).Scan(&latest, &earliest); err != nil {+ return 0, err+ }if !latest.Valid || !earliest.Valid {- return 0+ return 0, nil}- return latest.Float64 - earliest.Float64+ return latest.Float64 - earliest.Float64, nil}diff --git a/backend/utils/dberr.go b/backend/utils/dberr.goindex ba270eb..e806217 100644--- a/backend/utils/dberr.go+++ b/backend/utils/dberr.go@@ -44,6 +44,13 @@ func IsUniqueViolation(err error) bool {}}+// IsForeignKeyViolation reports whether err is a FOREIGN KEY constraint failure,+// i.e. a write referencing a row that doesn't exist — a client error, not an+// internal one.+func IsForeignKeyViolation(err error) bool {+ return sqliteCode(err) == sqlitelib.SQLITE_CONSTRAINT_FOREIGNKEY+}+// DBError maps a database error to an HTTP response and reports whether it wrote// one. It deliberately ignores nil and sql.ErrNoRows: "no rows" means something// different per endpoint (401, 404, an empty 200), so each caller handles that