loadExercises scans + closes the parent cursor BEFORE loading each exercise's sets (#36), and surfaces scan errors.
(programID int64)
| 178 | for i := range ids { |
| 179 | idSelects[i] = "SELECT ? AS program_id" |
| 180 | inPlaceholders[i] = "?" |
| 181 | } |
| 182 | idsCSV := strings.Join(inPlaceholders, ",") |
| 183 | |
| 184 | query := ` |
| 185 | WITH ids(program_id) AS (` + strings.Join(idSelects, " UNION ALL ") + `), |
| 186 | anchors AS ( |
| 187 | SELECT w.program_id AS program_id, w.program_day_id AS anchor_day_id, |
| 188 | w.id AS anchor_wid, w.started_at AS anchor_started_at |
| 189 | FROM workouts w |
| 190 | JOIN program_days pd ON pd.id = w.program_day_id |
| 191 | WHERE w.user_id = ? AND pd.is_rest_day = 0 AND w.program_id IN (` + idsCSV + `) |
| 192 | AND NOT EXISTS ( |
| 193 | SELECT 1 FROM workouts w2 |
| 194 | JOIN program_days pd2 ON pd2.id = w2.program_day_id |
| 195 | WHERE w2.user_id = w.user_id AND w2.program_id = w.program_id AND pd2.is_rest_day = 0 |
| 196 | AND (w2.started_at > w.started_at OR (w2.started_at = w.started_at AND w2.id > w.id)) |
| 197 | ) |
| 198 | ) |
| 199 | SELECT ids.program_id, a.anchor_day_id, a.anchor_wid, a.anchor_started_at, |
| 200 | (SELECT COUNT(*) FROM workouts w |
| 201 | WHERE w.user_id = ? AND w.program_id = ids.program_id |
| 202 | AND w.program_day_id IS NULL AND w.program_day_dropped = 0 |
| 203 | AND (a.anchor_started_at IS NULL |
| 204 | OR w.started_at > a.anchor_started_at |
| 205 | OR (w.started_at = a.anchor_started_at AND w.id > a.anchor_wid)) |
| 206 | ) AS unlinked |
| 207 | FROM ids |
| 208 | LEFT JOIN anchors a ON a.program_id = ids.program_id` |
| 209 | |
| 210 | args := make([]any, 0, 2*len(ids)+2) |
| 211 | for _, id := range ids { |
| 212 | args = append(args, id) |
| 213 | } |
| 214 | args = append(args, uid) |
| 215 | for _, id := range ids { |
| 216 | args = append(args, id) |
| 217 | } |
| 218 | args = append(args, uid) |
| 219 | |
| 220 | rows, err := s.db.Query(query, args...) |
| 221 | if err != nil { |
| 222 | return nil, err |
| 223 | } |