Files
geniusrun/backend/internal/store/laps.go
Christophe Vila 47dbf4e446 store: scope kind assignments, laps, and samples via activity ownership
None of these three tables gained their own user_id column -- they're
always accessed through a specific activity, so ownership is checked via a
join/subquery against activities.user_id instead.
2026-07-25 17:27:51 +02:00

110 lines
4.1 KiB
Go

package store
import (
"context"
"database/sql"
"fmt"
)
// Lap is one lap/split of an activity, from get_activity_splits, plus
// derived HR drift/recovery metrics computed from activity_samples.
//
// Deliberately NOT modeled here: StartTimeUTC, DistanceMeters, MaxHR,
// MaxSpeedMps, ElevationGainM, ElevationLossM (removed in the 2026-07
// dedup pass -- zero consumers anywhere, pure duplicates of RawJSON), plus
// DurationSeconds and AvgHR, which DO have a real frontend chart need but no
// backend one, so the API layer decodes them from RawJSON at response time
// instead of storing a redundant copy -- see decodeLapDisplayFields.
type Lap struct {
ID int64
ActivityID int64
LapIndex int
AvgSpeedMps *float64
IntensityType string
HRDriftBpmPerMin *float64
HRRecoveryBpmPerMin *float64
// TargetPaceLowMps/High and TargetHRLowBpm/High hold the expected band
// for this lap, resolved from the activity's structured Garmin workout
// (see internal/sync's alignWorkoutTargets) when its steps line up 1:1
// with the recorded laps. Nil when the activity has no structured
// workout, the step counts don't match, or the step targets neither
// pace nor heart rate.
TargetPaceLowMps *float64
TargetPaceHighMps *float64
TargetHRLowBpm *float64
TargetHRHighBpm *float64
RawJSON string
}
// ReplaceLaps deletes any existing laps for activityID (owned by userID)
// and inserts the given set, so re-syncing an activity's splits is
// idempotent.
func (db *DB) ReplaceLaps(ctx context.Context, userID, activityID int64, laps []Lap) error {
var exists int
err := db.QueryRowContext(ctx, `SELECT 1 FROM activities WHERE id = ? AND user_id = ?`, activityID, userID).Scan(&exists)
if err == sql.ErrNoRows {
return fmt.Errorf("replace laps: activity %d not found for user %d", activityID, userID)
}
if err != nil {
return fmt.Errorf("replace laps for activity %d (user %d): %w", activityID, userID, err)
}
tx, err := db.BeginTx(ctx, nil)
if err != nil {
return fmt.Errorf("begin replace laps tx: %w", err)
}
defer tx.Rollback()
if _, err := tx.ExecContext(ctx, `DELETE FROM laps WHERE activity_id = ?`, activityID); err != nil {
return fmt.Errorf("delete existing laps for activity %d: %w", activityID, err)
}
for _, l := range laps {
_, err := tx.ExecContext(ctx, `
INSERT INTO laps (
activity_id, lap_index, avg_speed_mps,
intensity_type, hr_drift_bpm_per_min, hr_recovery_bpm_per_min,
target_pace_low_mps, target_pace_high_mps, target_hr_low_bpm, target_hr_high_bpm, raw_json
) VALUES (?,?,?,?,?,?,?,?,?,?,?)`,
activityID, l.LapIndex, l.AvgSpeedMps,
l.IntensityType, l.HRDriftBpmPerMin, l.HRRecoveryBpmPerMin,
l.TargetPaceLowMps, l.TargetPaceHighMps, l.TargetHRLowBpm, l.TargetHRHighBpm, l.RawJSON,
)
if err != nil {
return fmt.Errorf("insert lap %d for activity %d: %w", l.LapIndex, activityID, err)
}
}
return tx.Commit()
}
// LapsForActivity returns all laps for an activity owned by userID,
// ordered by lap_index.
func (db *DB) LapsForActivity(ctx context.Context, userID, activityID int64) ([]Lap, error) {
rows, err := db.QueryContext(ctx, `
SELECT laps.id, laps.activity_id, laps.lap_index, laps.avg_speed_mps,
laps.intensity_type, laps.hr_drift_bpm_per_min, laps.hr_recovery_bpm_per_min,
laps.target_pace_low_mps, laps.target_pace_high_mps, laps.target_hr_low_bpm, laps.target_hr_high_bpm, laps.raw_json
FROM laps
JOIN activities ON activities.id = laps.activity_id
WHERE laps.activity_id = ? AND activities.user_id = ?
ORDER BY laps.lap_index`, activityID, userID)
if err != nil {
return nil, fmt.Errorf("laps for activity %d (user %d): %w", activityID, userID, err)
}
defer rows.Close()
laps := []Lap{}
for rows.Next() {
var l Lap
if err := rows.Scan(
&l.ID, &l.ActivityID, &l.LapIndex, &l.AvgSpeedMps,
&l.IntensityType, &l.HRDriftBpmPerMin, &l.HRRecoveryBpmPerMin,
&l.TargetPaceLowMps, &l.TargetPaceHighMps, &l.TargetHRLowBpm, &l.TargetHRHighBpm, &l.RawJSON,
); err != nil {
return nil, fmt.Errorf("scan lap row: %w", err)
}
laps = append(laps, l)
}
return laps, rows.Err()
}