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.
This commit is contained in:
2026-07-25 17:27:51 +02:00
parent f82549524b
commit 47dbf4e446
5 changed files with 163 additions and 75 deletions

View File

@@ -2,6 +2,7 @@ package store
import (
"context"
"database/sql"
"fmt"
)
@@ -35,9 +36,19 @@ type Lap struct {
RawJSON string
}
// ReplaceLaps deletes any existing laps for activityID and inserts the given
// set, so re-syncing an activity's splits is idempotent.
func (db *DB) ReplaceLaps(ctx context.Context, activityID int64, laps []Lap) error {
// 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)
@@ -66,15 +77,19 @@ func (db *DB) ReplaceLaps(ctx context.Context, activityID int64, laps []Lap) err
return tx.Commit()
}
// LapsForActivity returns all laps for an activity, ordered by lap_index.
func (db *DB) LapsForActivity(ctx context.Context, activityID int64) ([]Lap, error) {
// 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 id, 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
FROM laps WHERE activity_id = ? ORDER BY lap_index`, activityID)
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: %w", activityID, err)
return nil, fmt.Errorf("laps for activity %d (user %d): %w", activityID, userID, err)
}
defer rows.Close()