summaryrefslogtreecommitdiff
path: root/internal/store/estimate_inference.go
blob: d0a0034da515bb988f25b8d8489d0b6ee464b945 (plain)
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
package store

import "encoding/json"

// AverageEstimateForProject returns the rounded average estimated_minutes
// across all user-estimated (estimated_minutes > 0) tasks under projectID.
// ok is false when no such task exists -- there's no signal to infer from.
func (s *Store) AverageEstimateForProject(projectID string) (int, bool, error) {
	var sum, count int
	rows, err := s.db.Query(`SELECT estimated_minutes FROM native_tasks WHERE project_id = ? AND estimated_minutes > 0`, projectID)
	if err != nil {
		return 0, false, err
	}
	defer func() { _ = rows.Close() }()
	for rows.Next() {
		var minutes int
		if err := rows.Scan(&minutes); err != nil {
			return 0, false, err
		}
		sum += minutes
		count++
	}
	if err := rows.Err(); err != nil {
		return 0, false, err
	}
	if count == 0 {
		return 0, false, nil
	}
	return sum / count, true, nil
}

// AverageEstimateForLabel returns the rounded average estimated_minutes
// across all user-estimated tasks carrying the given label. Labels are
// stored as a JSON array column, not a joinable table, so this scans every
// estimated task and filters in Go rather than risking a SQL substring
// false-positive (e.g. LIKE '%"run"%' matching a task labeled "running").
func (s *Store) AverageEstimateForLabel(label string) (int, bool, error) {
	rows, err := s.db.Query(`SELECT labels, estimated_minutes FROM native_tasks WHERE estimated_minutes > 0`)
	if err != nil {
		return 0, false, err
	}
	defer func() { _ = rows.Close() }()

	var sum, count int
	for rows.Next() {
		var labelsJSON string
		var minutes int
		if err := rows.Scan(&labelsJSON, &minutes); err != nil {
			return 0, false, err
		}
		var labels []string
		if err := json.Unmarshal([]byte(labelsJSON), &labels); err != nil {
			continue
		}
		for _, l := range labels {
			if l == label {
				sum += minutes
				count++
				break
			}
		}
	}
	if err := rows.Err(); err != nil {
		return 0, false, err
	}
	if count == 0 {
		return 0, false, nil
	}
	return sum / count, true, nil
}