aboutsummaryrefslogtreecommitdiff
path: root/rides/rides.go
blob: 94fbc64ddb5301b459ea353b8e6195cc7877851d (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269

package rides

import (
	"database/sql"
	"fmt"
	"log/slog"
	"time"

	"github.com/martinlehoux/biking_home/ride"
	"github.com/martinlehoux/kagamigo/kcore"
)

type Ride struct {
	ID                    int64
	ExternalID            string
	GPXPath               string
	Name                  string
	Type                  string
	StartDate             time.Time
	DistanceM             float64
	ExternalMovingTimeS   int64
	movingTimeS           *int64
	movingTimeAlgoVersion string
	ElapsedTimeS          int64
	TotalElevationGainM   float64
	AverageSpeedMps       float64
	cotacolScore          *float64
	cotacolAlgoVersion    string
	CreatedAt             time.Time
	UpdatedAt             time.Time
}

type SortColumn string

const (
	SortName       SortColumn = "name"
	SortStartDate  SortColumn = "started"
	SortDistance   SortColumn = "distance"
	SortMovingTime SortColumn = "moving_time"
	SortSpeed      SortColumn = "speed"
	SortElevation  SortColumn = "elevation"
	SortCotacol    SortColumn = "cotacol"
	SortCotacolKm  SortColumn = "cotacol_100km"
)

const columns = "id, external_id, gpx_path, name, type, start_date, distance_m, external_moving_time_s, moving_time_s, moving_time_algo_version, elapsed_time_s, total_elevation_gain_m, average_speed_mps, cotacol_score, cotacol_algo_version, created_at, updated_at"

func Save(db *sql.DB, r Ride) error {
	var cotacolScore any
	var cotacolAlgorithmVersion any
	var movingTimeS any
	var movingTimeAlgorithmVersion any
	if r.GPXPath != "" {
		parsed, err := ride.ParseFile(ride.GPXRideParser{}, r.GPXPath)
		if err != nil {
			return fmt.Errorf("compute ride values for %q: %w", r.ExternalID, err)
		}
		cotacolScore = ride.Cotacol(parsed)
		cotacolAlgorithmVersion = ride.CotacolAlgorithmVersion
		movingTimeS = int64(ride.MovingTime(parsed) / time.Second)
		movingTimeAlgorithmVersion = ride.MovingTimeAlgorithmVersion
	}
	_, err := db.Exec(`
		INSERT INTO rides (external_id, gpx_path, name, type, start_date, distance_m, external_moving_time_s, moving_time_s, moving_time_algo_version, elapsed_time_s, total_elevation_gain_m, average_speed_mps, cotacol_score, cotacol_algo_version)
		VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)
		ON CONFLICT(external_id) DO UPDATE SET
			gpx_path = excluded.gpx_path,
			name = excluded.name,
			type = excluded.type,
			start_date = excluded.start_date,
			distance_m = excluded.distance_m,
			external_moving_time_s = excluded.external_moving_time_s,
			moving_time_s = excluded.moving_time_s,
			moving_time_algo_version = excluded.moving_time_algo_version,
			elapsed_time_s = excluded.elapsed_time_s,
			total_elevation_gain_m = excluded.total_elevation_gain_m,
			average_speed_mps = excluded.average_speed_mps,
			cotacol_score = excluded.cotacol_score,
			cotacol_algo_version = excluded.cotacol_algo_version,
			updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now')
	`, r.ExternalID, r.GPXPath, r.Name, r.Type, r.StartDate.UTC().Format(time.RFC3339), r.DistanceM, r.ExternalMovingTimeS, movingTimeS, movingTimeAlgorithmVersion, r.ElapsedTimeS, r.TotalElevationGainM, r.AverageSpeedMps, cotacolScore, cotacolAlgorithmVersion)
	return err
}

func Backfill(db *sql.DB) (int, error) {
	rows, err := db.Query("SELECT " + columns + " FROM rides ORDER BY id")
	if err != nil {
		return 0, err
	}
	var pending []Ride
	for rows.Next() {
		item, err := scanRide(rows)
		if err != nil {
			rows.Close()
			return 0, err
		}
		pending = append(pending, item)
	}
	if err := rows.Err(); err != nil {
		rows.Close()
		return 0, err
	}
	if err := rows.Close(); err != nil {
		return 0, err
	}
	backfilled := 0
	for _, item := range pending {
		if err := Save(db, item); err != nil {
			slog.Warn("Failed to backfill ride values", "ride", item.ExternalID, "file", item.GPXPath, "error", err)
			continue
		}
		backfilled++
	}
	return backfilled, nil
}

func List(db *sql.DB) ([]Ride, error) {
	return ListSorted(db, SortStartDate, true)
}

func ListSorted(db *sql.DB, column SortColumn, descending bool) ([]Ride, error) {
	expression, ok := sortExpressions[column]
	if !ok {
		return nil, fmt.Errorf("invalid ride sort column %q", column)
	}
	direction := "ASC"
	if descending {
		direction = "DESC"
	}
	query := "SELECT " + columns + " FROM rides ORDER BY "
	args := []any{}
	if column == SortMovingTime {
		args = append(args, ride.MovingTimeAlgorithmVersion)
	} else if isComputedSort(column) {
		query += "(cotacol_score IS NULL OR cotacol_algo_version IS NULL OR cotacol_algo_version <> ? OR distance_m <= 0) ASC, "
		args = append(args, ride.CotacolAlgorithmVersion)
	}
	query += expression + " " + direction + ", id DESC"
	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var rides []Ride
	for rows.Next() {
		ride, err := scanRide(rows)
		if err != nil {
			return nil, err
		}
		rides = append(rides, ride)
	}
	return rides, rows.Err()
}

var sortExpressions = map[SortColumn]string{
	SortName:       "name COLLATE NOCASE",
	SortStartDate:  "start_date",
	SortDistance:   "distance_m",
	SortMovingTime: "CASE WHEN moving_time_algo_version = ? THEN COALESCE(moving_time_s, external_moving_time_s) ELSE external_moving_time_s END",
	SortSpeed:      "average_speed_mps",
	SortElevation:  "total_elevation_gain_m",
	SortCotacol:    "cotacol_score",
	SortCotacolKm:  "cotacol_score * 100000.0 / NULLIF(distance_m, 0)",
}

func isComputedSort(column SortColumn) bool {
	return column == SortCotacol || column == SortCotacolKm
}

func GetByExternalID(db *sql.DB, externalID string) (Ride, bool, error) {
	row := db.QueryRow("SELECT "+columns+" FROM rides WHERE external_id = ?", externalID)
	ride, err := scanRide(row)
	if err == sql.ErrNoRows {
		return Ride{}, false, nil
	}
	if err != nil {
		return Ride{}, false, err
	}
	return ride, true, nil
}

func GetByID(db *sql.DB, id int64) (Ride, bool, error) {
	row := db.QueryRow("SELECT "+columns+" FROM rides WHERE id = ?", id)
	ride, err := scanRide(row)
	if err == sql.ErrNoRows {
		return Ride{}, false, nil
	}
	if err != nil {
		return Ride{}, false, err
	}
	return ride, true, nil
}

type scanner interface {
	Scan(dest ...any) error
}

func scanRide(s scanner) (Ride, error) {
	var (
		ride               Ride
		startDate          string
		movingTimeS        sql.NullInt64
		movingTimeAlgoVer  sql.NullString
		cotacolScore       sql.NullFloat64
		cotacolAlgoVersion sql.NullString
		createdAt          string
		updatedAt          string
	)
	err := s.Scan(&ride.ID, &ride.ExternalID, &ride.GPXPath, &ride.Name, &ride.Type, &startDate, &ride.DistanceM, &ride.ExternalMovingTimeS, &movingTimeS, &movingTimeAlgoVer, &ride.ElapsedTimeS, &ride.TotalElevationGainM, &ride.AverageSpeedMps, &cotacolScore, &cotacolAlgoVersion, &createdAt, &updatedAt)
	if err != nil {
		return Ride{}, err
	}
	if movingTimeS.Valid {
		ride.movingTimeS = &movingTimeS.Int64
	}
	if movingTimeAlgoVer.Valid {
		ride.movingTimeAlgoVersion = movingTimeAlgoVer.String
	}
	if cotacolScore.Valid {
		ride.cotacolScore = &cotacolScore.Float64
	}
	if cotacolAlgoVersion.Valid {
		ride.cotacolAlgoVersion = cotacolAlgoVersion.String
	}
	ride.StartDate, err = time.Parse(time.RFC3339, startDate)
	if err != nil {
		return Ride{}, kcore.Wrap(err, "invalid start_date in rides row")
	}
	ride.CreatedAt, err = time.Parse(time.RFC3339, createdAt)
	if err != nil {
		return Ride{}, kcore.Wrap(err, "invalid created_at in rides row")
	}
	ride.UpdatedAt, err = time.Parse(time.RFC3339, updatedAt)
	if err != nil {
		return Ride{}, kcore.Wrap(err, "invalid updated_at in rides row")
	}
	return ride, nil
}

func (r Ride) CotacolAlgorithmVersion() string {
	return r.cotacolAlgoVersion
}

func (r Ride) MovingTimeS() (int64, bool) {
	if r.movingTimeS == nil {
		return 0, false
	}
	return *r.movingTimeS, true
}

func (r Ride) MovingTimeAlgorithmVersion() string {
	return r.movingTimeAlgoVersion
}

// EffectiveMovingTimeS is the canonical moving time when the stored value
// matches the current algorithm version, falling back to Strava's value.
func (r Ride) EffectiveMovingTimeS() int64 {
	if moving, ok := r.MovingTimeS(); ok && r.movingTimeAlgoVersion == ride.MovingTimeAlgorithmVersion {
		return moving
	}
	return r.ExternalMovingTimeS
}

func (r Ride) CotacolScore() (float64, bool) {
	if r.cotacolScore == nil {
		return 0, false
	}
	return *r.cotacolScore, true
}