aboutsummaryrefslogtreecommitdiff
path: root/ride/store.go
blob: 2d022ad656ef3efc8cf5ef367da9157d1b184a94 (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
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370

package ride

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

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

type StoredRide 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
	BikeType              BikeType
	RideType              RideType
	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, bike_type, ride_type, created_at, updated_at"

func Save(db *sql.DB, r StoredRide) error {
	var cotacolScore any
	var cotacolAlgorithmVersion any
	var movingTimeS any
	var movingTimeAlgorithmVersion any
	if r.GPXPath != "" {
		parsed, err := ParseFile(GPXRideParser{}, r.GPXPath)
		if err != nil {
			return fmt.Errorf("compute ride values for %q: %w", r.ExternalID, err)
		}
		cotacolScore = Cotacol(parsed)
		cotacolAlgorithmVersion = CotacolAlgorithmVersion
		movingTimeS = int64(MovingTime(parsed) / time.Second)
		movingTimeAlgorithmVersion = MovingTimeAlgorithmVersion
	}
	if !IsValidOrEmptyBikeType(string(r.BikeType)) {
		return fmt.Errorf("invalid bike_type %q", r.BikeType)
	}
	if !IsValidOrEmptyRideType(string(r.RideType)) {
		return fmt.Errorf("invalid ride_type %q", r.RideType)
	}
	_, 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, bike_type, ride_type)
		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,
			bike_type = CASE WHEN excluded.bike_type = '' THEN rides.bike_type ELSE excluded.bike_type END,
			ride_type = CASE WHEN excluded.ride_type = '' THEN rides.ride_type ELSE excluded.ride_type END,
			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, string(r.BikeType), string(r.RideType))
	return err
}

// Backfill recomputes and persists stored ride values for every ride. An
// optional reporter is invoked with the number of rides processed and the
// total, so callers (e.g. the CLI) can render progress.
func Backfill(db *sql.DB, reporters ...func(current, total int)) (int, error) {
	rows, err := db.Query("SELECT " + columns + " FROM rides ORDER BY id")
	if err != nil {
		return 0, err
	}
	var pending []StoredRide
	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
	report := func(int, int) {}
	if len(reporters) > 0 {
		report = reporters[0]
	}
	for i, item := range pending {
		report(i+1, len(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) ([]StoredRide, error) {
	return ListSorted(db, SortStartDate, true)
}

func ListSorted(db *sql.DB, column SortColumn, descending bool) ([]StoredRide, 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, 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, CotacolAlgorithmVersion)
	}
	query += expression + " " + direction + ", id DESC"
	rows, err := db.Query(query, args...)
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var rides []StoredRide
	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) (StoredRide, bool, error) {
	row := db.QueryRow("SELECT "+columns+" FROM rides WHERE external_id = ?", externalID)
	ride, err := scanRide(row)
	if err == sql.ErrNoRows {
		return StoredRide{}, false, nil
	}
	if err != nil {
		return StoredRide{}, false, err
	}
	return ride, true, nil
}

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

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

func scanRide(s scanner) (StoredRide, error) {
	var (
		ride               StoredRide
		startDate          string
		movingTimeS        sql.NullInt64
		movingTimeAlgoVer  sql.NullString
		cotacolScore       sql.NullFloat64
		cotacolAlgoVersion sql.NullString
		bikeType           string
		rideType           string
		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, &bikeType, &rideType, &createdAt, &updatedAt)
	if err != nil {
		return StoredRide{}, 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.BikeType = BikeType(bikeType)
	ride.RideType = RideType(rideType)
	ride.StartDate, err = time.Parse(time.RFC3339, startDate)
	if err != nil {
		return StoredRide{}, kcore.Wrap(err, "invalid start_date in rides row")
	}
	ride.CreatedAt, err = time.Parse(time.RFC3339, createdAt)
	if err != nil {
		return StoredRide{}, kcore.Wrap(err, "invalid created_at in rides row")
	}
	ride.UpdatedAt, err = time.Parse(time.RFC3339, updatedAt)
	if err != nil {
		return StoredRide{}, kcore.Wrap(err, "invalid updated_at in rides row")
	}
	return ride, nil
}

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

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

func (r StoredRide) 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 StoredRide) EffectiveMovingTimeS() int64 {
	if moving, ok := r.MovingTimeS(); ok && r.movingTimeAlgoVersion == MovingTimeAlgorithmVersion {
		return moving
	}
	return r.ExternalMovingTimeS
}

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

func (r StoredRide) IsCategorised() bool {
	return r.BikeType != "" && r.RideType != ""
}

func UpdateCategories(db *sql.DB, id int64, bikeType BikeType, rideType RideType) error {
	if !IsValidBikeType(string(bikeType)) {
		return fmt.Errorf("invalid bike_type %q", bikeType)
	}
	if !IsValidRideType(string(rideType)) {
		return fmt.Errorf("invalid ride_type %q", rideType)
	}
	result, err := db.Exec(`UPDATE rides SET bike_type = ?, ride_type = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id = ?`, string(bikeType), string(rideType), id)
	if err != nil {
		return err
	}
	affected, err := result.RowsAffected()
	if err != nil {
		return err
	}
	if affected == 0 {
		return sql.ErrNoRows
	}
	return nil
}

func BulkUpdateCategories(db *sql.DB, ids []int64, bikeType BikeType, rideType RideType) (int64, error) {
	if len(ids) == 0 {
		return 0, nil
	}
	if !IsValidBikeType(string(bikeType)) {
		return 0, fmt.Errorf("invalid bike_type %q", bikeType)
	}
	if !IsValidRideType(string(rideType)) {
		return 0, fmt.Errorf("invalid ride_type %q", rideType)
	}
	var query strings.Builder
	query.WriteString("UPDATE rides SET bike_type = ?, ride_type = ?, updated_at = strftime('%Y-%m-%dT%H:%M:%SZ', 'now') WHERE id IN (")
	args := []any{string(bikeType), string(rideType)}
	for i, id := range ids {
		if i > 0 {
			query.WriteString(",")
		}
		query.WriteString("?")
		args = append(args, id)
	}
	query.WriteString(")")
	result, err := db.Exec(query.String(), args...)
	if err != nil {
		return 0, err
	}
	return result.RowsAffected()
}

func CountUncategorised(db *sql.DB) (int, error) {
	row := db.QueryRow(`SELECT COUNT(*) FROM rides WHERE bike_type = '' OR ride_type = ''`)
	var count int
	if err := row.Scan(&count); err != nil {
		return 0, err
	}
	return count, nil
}

func ListUncategorised(db *sql.DB) ([]StoredRide, error) {
	rows, err := db.Query("SELECT " + columns + " FROM rides WHERE bike_type = '' OR ride_type = '' ORDER BY start_date DESC, id DESC")
	if err != nil {
		return nil, err
	}
	defer rows.Close()
	var rides []StoredRide
	for rows.Next() {
		ride, err := scanRide(rows)
		if err != nil {
			return nil, err
		}
		rides = append(rides, ride)
	}
	return rides, rows.Err()
}