summaryrefslogtreecommitdiff
path: root/internal/store/annotation.go
blob: 84b0c486f7fcfc4dac7f6d189af2dabfa2cc49e6 (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
package store

import "fmt"

// Annotation holds optional comment and highlight colour for a history row.
type Annotation struct {
	HistoryID uint64
	Comment   string
	Color     string // empty means no highlight; one of: "red", "orange", "yellow", "green", "blue", "purple"
}

// SetAnnotation creates or replaces the annotation for the given history row.
func (s *Store) SetAnnotation(a Annotation) error {
	return s.write(func() error {
		_, err := s.db.Exec(`
			INSERT INTO annotations (history_id, comment, color)
			VALUES (?, ?, ?)
			ON CONFLICT(history_id) DO UPDATE SET
				comment = excluded.comment,
				color   = excluded.color`,
			a.HistoryID, a.Comment, a.Color,
		)
		if err != nil {
			return fmt.Errorf("store: set annotation %d: %w", a.HistoryID, err)
		}
		return nil
	})
}

// DeleteAnnotation removes the annotation for the given history row.
func (s *Store) DeleteAnnotation(historyID uint64) error {
	return s.write(func() error {
		_, err := s.db.Exec(`DELETE FROM annotations WHERE history_id = ?`, historyID)
		if err != nil {
			return fmt.Errorf("store: delete annotation %d: %w", historyID, err)
		}
		return nil
	})
}

// AllAnnotations returns every annotation row. Called once at startup to
// populate the in-memory annotation map.
func (s *Store) AllAnnotations() ([]Annotation, error) {
	rows, err := s.db.Query(`SELECT history_id, comment, color FROM annotations`)
	if err != nil {
		return nil, fmt.Errorf("store: all annotations: %w", err)
	}
	defer rows.Close()
	var out []Annotation
	for rows.Next() {
		var a Annotation
		if err := rows.Scan(&a.HistoryID, &a.Comment, &a.Color); err != nil {
			return nil, fmt.Errorf("store: scan annotation: %w", err)
		}
		out = append(out, a)
	}
	return out, rows.Err()
}