| 1 | package store |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "fmt" |
| 6 | "strconv" |
| 7 | "strings" |
| 8 | "time" |
| 9 | ) |
| 10 | |
| 11 | // Note is een reactie op een merge request. |
| 12 | type Note struct { |
| 13 | ID int64 |
| 14 | RepoID int64 |
| 15 | MRID int64 |
| 16 | AuthorID int64 |
| 17 | Author string |
| 18 | Body string |
| 19 | CreatedAt time.Time |
| 20 | } |
| 21 | |
| 22 | // AddNote bewaart een reactie en telt hem als bijdrage. |
| 23 | func (s *Store) AddNote(ctx context.Context, repoID, mrID, authorID int64, body string) (Note, error) { |
| 24 | body = strings.TrimSpace(body) |
| 25 | if body == "" { |
| 26 | return Note{}, fmt.Errorf("een reactie is leeg") |
| 27 | } |
| 28 | body = trim(body, 4000) |
| 29 | tx, err := s.db.BeginTx(ctx, nil) |
| 30 | if err != nil { |
| 31 | return Note{}, err |
| 32 | } |
| 33 | defer func() { _ = tx.Rollback() }() |
| 34 | ts := now() |
| 35 | res, err := tx.ExecContext(ctx, `INSERT INTO notes (repo_id, mr_id, author_id, body, created_at) VALUES (?, ?, ?, ?, ?)`, |
| 36 | repoID, mrID, authorID, body, ts) |
| 37 | if err != nil { |
| 38 | return Note{}, err |
| 39 | } |
| 40 | id, _ := res.LastInsertId() |
| 41 | if _, err := tx.ExecContext(ctx, `INSERT OR IGNORE INTO contributions (user_id, repo_id, kind, ref, occurred_at) VALUES (?, ?, 'comment', ?, ?)`, |
| 42 | authorID, repoID, "note:"+strconv.FormatInt(id, 10), ts); err != nil { |
| 43 | return Note{}, err |
| 44 | } |
| 45 | if err := tx.Commit(); err != nil { |
| 46 | return Note{}, err |
| 47 | } |
| 48 | return Note{ID: id, RepoID: repoID, MRID: mrID, AuthorID: authorID, Body: body, CreatedAt: parseTime(ts)}, nil |
| 49 | } |
| 50 | |
| 51 | // ListNotes geeft de reacties van één merge request, oudste eerst. |
| 52 | func (s *Store) ListNotes(ctx context.Context, mrID int64) ([]Note, error) { |
| 53 | rows, err := s.db.QueryContext(ctx, `SELECT n.id, n.repo_id, n.mr_id, n.author_id, u.username, n.body, n.created_at |
| 54 | FROM notes n JOIN users u ON u.id = n.author_id WHERE n.mr_id = ? ORDER BY n.id`, mrID) |
| 55 | if err != nil { |
| 56 | return nil, err |
| 57 | } |
| 58 | defer rows.Close() |
| 59 | var out []Note |
| 60 | for rows.Next() { |
| 61 | var n Note |
| 62 | var created string |
| 63 | if err := rows.Scan(&n.ID, &n.RepoID, &n.MRID, &n.AuthorID, &n.Author, &n.Body, &created); err != nil { |
| 64 | return nil, err |
| 65 | } |
| 66 | n.CreatedAt = parseTime(created) |
| 67 | out = append(out, n) |
| 68 | } |
| 69 | return out, rows.Err() |
| 70 | } |