internal/store/dashboard.go
339 lines · 12771 bytes
26 symbols in this file
DashboardItemreachableCondinvolvedCondStore.dashboardQuerydashboardMRsQueryStore.DashboardMRsdashboardIssuesQueryStore.DashboardIssuesStore.PinRepoStore.IsPinnedStore.UnpinRepoStore.PinnedReposreviewQueueQueryrequestedReviewsQueryStore.ReviewQueueStore.OpenCountsassignedIssuesQueryStore.AssignedIssuesDashboardBuildStore.RecentBuildsFeedEventStore.OwnerPublicEventsStore.UserPublicEventsStore.RecentEventsfeedSelectscanFeedEvent
1package store
2
3import "sort"
4
5// DashboardItem is one open issue or MR row on the logged-in homepage.
6type DashboardItem struct {
7 RepoPath string
8 Number int64
9 Title string
10 Author string
11 State string
12 UpdatedAt string
13 Queued bool // a merge request with a queued merge
14}
15
16// reachableCond filters to repositories the user owns, is granted on, or
17// reaches through org or team membership.
18const reachableCond = `(
19 (r.owner_kind = 'user' AND r.owner_id = ?1)
20 OR EXISTS (SELECT 1 FROM repo_access a
21 WHERE a.repo_id = r.id AND a.subject_kind = 'user' AND a.subject_id = ?1)
22 OR EXISTS (SELECT 1 FROM org_members mm
23 JOIN orgs oo ON oo.id = mm.org_id
24 WHERE r.owner_kind = 'org' AND mm.org_id = r.owner_id AND mm.user_id = ?1
25 AND (mm.role = 'admin' OR oo.members_role <> 'none'))
26 OR EXISTS (SELECT 1 FROM team_repos tr
27 JOIN team_members tm ON tm.team_id = tr.team_id AND tm.user_id = ?1
28 WHERE tr.repo_id = r.id)
29)`
30
31// involvedCond widens reachableCond to rows the user authored anywhere.
32const involvedCond = `(x.author_id = ?1 OR ` + reachableCond + `)`
33
34func (s *Store) dashboardQuery(q string, userID int64) ([]DashboardItem, error) {
35 rows, err := s.DB.Query(q, userID)
36 if err != nil {
37 return nil, err
38 }
39 defer rows.Close()
40 var out []DashboardItem
41 for rows.Next() {
42 var d DashboardItem
43 if err := rows.Scan(&d.RepoPath, &d.Number, &d.Title, &d.Author, &d.State, &d.UpdatedAt, &d.Queued); err != nil {
44 return nil, err
45 }
46 out = append(out, d)
47 }
48 return out, rows.Err()
49}
50
51// The dashboard's four list queries are named so the plan test can assert
52// each still walks the 0035 index that supplies its ORDER BY.
53const dashboardMRsQuery = `
54 SELECT COALESCE(u.username, o.name) || '/' || r.name,
55 x.number, x.title, au.username, x.state, x.updated_at,
56 EXISTS (SELECT 1 FROM mr_merge_queue q WHERE q.mr_id = x.id)
57 FROM merge_requests x
58 JOIN repos r ON r.id = x.repo_id
59 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
60 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
61 JOIN users au ON au.id = x.author_id
62 WHERE x.state IN ('open', 'source_gone') AND ` + involvedCond + `
63 ORDER BY x.updated_at DESC, x.id DESC LIMIT 50`
64
65// DashboardMRs returns open merge requests involving the user: on their
66// repositories (owned, granted, org) or authored by them anywhere.
67func (s *Store) DashboardMRs(userID int64) ([]DashboardItem, error) {
68 return s.dashboardQuery(dashboardMRsQuery, userID)
69}
70
71// DashboardIssues is the issue counterpart of DashboardMRs.
72const dashboardIssuesQuery = `
73 SELECT COALESCE(u.username, o.name) || '/' || r.name,
74 x.number, x.title, au.username, x.state, x.updated_at, 0
75 FROM issues x
76 JOIN repos r ON r.id = x.repo_id
77 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
78 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
79 JOIN users au ON au.id = x.author_id
80 WHERE x.state = 'open' AND ` + involvedCond + `
81 AND NOT EXISTS (SELECT 1 FROM issue_assignees ia
82 WHERE ia.issue_id = x.id AND ia.user_id = ?1)
83 ORDER BY x.updated_at DESC, x.id DESC LIMIT 50`
84
85func (s *Store) DashboardIssues(userID int64) ([]DashboardItem, error) {
86 return s.dashboardQuery(dashboardIssuesQuery, userID)
87}
88
89func (s *Store) PinRepo(userID, repoID int64) error {
90 _, err := s.DB.Exec(
91 "INSERT INTO repo_pins (user_id, repo_id) VALUES (?, ?) ON CONFLICT DO NOTHING",
92 userID, repoID)
93 return err
94}
95
96func (s *Store) IsPinned(userID, repoID int64) bool {
97 var n int
98 s.DB.QueryRow("SELECT COUNT(*) FROM repo_pins WHERE user_id = ? AND repo_id = ?",
99 userID, repoID).Scan(&n)
100 return n > 0
101}
102
103func (s *Store) UnpinRepo(userID, repoID int64) error {
104 res, err := s.DB.Exec(
105 "DELETE FROM repo_pins WHERE user_id = ? AND repo_id = ?", userID, repoID)
106 if err != nil {
107 return err
108 }
109 if n, _ := res.RowsAffected(); n == 0 {
110 return ErrNotFound
111 }
112 return nil
113}
114
115// PinnedRepos returns the user's pinned repositories in pin order. The
116// caller applies visibility checks before rendering.
117func (s *Store) PinnedRepos(userID int64) ([]Repo, error) {
118 return queryAll(s.DB, scanRepo, repoSelect+`
119 JOIN repo_pins p ON p.repo_id = r.id AND p.user_id = ?
120 ORDER BY p.pinned_at`, userID)
121}
122
123// reviewQueueQuery is ReviewQueue's involved half: open merge requests the
124// user is involved in, has not authored, and has not reviewed at the
125// current head.
126const reviewQueueQuery = `
127 SELECT COALESCE(u.username, o.name) || '/' || r.name,
128 x.number, x.title, au.username, x.state, x.updated_at,
129 EXISTS (SELECT 1 FROM mr_merge_queue q WHERE q.mr_id = x.id)
130 FROM merge_requests x
131 JOIN repos r ON r.id = x.repo_id
132 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
133 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
134 JOIN users au ON au.id = x.author_id
135 WHERE x.state IN ('open', 'source_gone')
136 AND x.draft = 0
137 AND x.author_id <> ?1
138 AND NOT EXISTS (SELECT 1 FROM mr_reviews rv
139 WHERE rv.mr_id = x.id AND rv.reviewer_id = ?1
140 AND rv.head_sha = x.head_sha)
141 AND ` + involvedCond + `
142 ORDER BY x.updated_at DESC, x.id DESC LIMIT 8`
143
144// requestedReviewsQuery is ReviewQueue's other half: MRs where the user was
145// asked directly, regardless of involvement — the same exemption
146// AssignedIssues gives assignment, and for the same reason (dashboard.go
147// above). It drives from mr_review_requests rather than testing EXISTS
148// against every merge request: one user's requests are a handful, the
149// merge_requests table is the whole instance.
150const requestedReviewsQuery = `
151 SELECT COALESCE(u.username, o.name) || '/' || r.name,
152 x.number, x.title, au.username, x.state, x.updated_at,
153 EXISTS (SELECT 1 FROM mr_merge_queue q WHERE q.mr_id = x.id)
154 FROM mr_review_requests rr
155 JOIN merge_requests x ON x.id = rr.mr_id
156 JOIN repos r ON r.id = x.repo_id
157 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
158 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
159 JOIN users au ON au.id = x.author_id
160 WHERE rr.user_id = ?1
161 AND x.state IN ('open', 'source_gone')
162 AND x.draft = 0
163 AND x.author_id <> ?1
164 AND NOT EXISTS (SELECT 1 FROM mr_reviews rv
165 WHERE rv.mr_id = x.id AND rv.reviewer_id = ?1
166 AND rv.head_sha = x.head_sha)
167 ORDER BY x.updated_at DESC, x.id DESC LIMIT 8`
168
169// ReviewQueue returns open merge requests the user is involved in, has not
170// authored, and has not reviewed at the current head — what the rail shows
171// as waiting on them — unioned with merge requests where they were asked
172// directly. Both halves drop an MR once its current head has been
173// reviewed, so a requested reviewer's queue empties the same way an
174// involved one's does. Ordered most recently touched first.
175func (s *Store) ReviewQueue(userID int64) ([]DashboardItem, error) {
176 involved, err := s.dashboardQuery(reviewQueueQuery, userID)
177 if err != nil {
178 return nil, err
179 }
180 requested, err := s.dashboardQuery(requestedReviewsQuery, userID)
181 if err != nil {
182 return nil, err
183 }
184 type key struct {
185 repo string
186 n int64
187 }
188 seen := make(map[key]bool, len(involved))
189 out := make([]DashboardItem, 0, len(involved)+len(requested))
190 for _, d := range involved {
191 seen[key{d.RepoPath, d.Number}] = true
192 out = append(out, d)
193 }
194 for _, d := range requested {
195 k := key{d.RepoPath, d.Number}
196 if !seen[k] {
197 seen[k] = true
198 out = append(out, d)
199 }
200 }
201 sort.SliceStable(out, func(i, j int) bool { return out[i].UpdatedAt > out[j].UpdatedAt })
202 if len(out) > 8 {
203 out = out[:8]
204 }
205 return out, nil
206}
207
208// OpenCounts returns the repo's open issue and open merge request counts,
209// for the repo tab badges.
210func (s *Store) OpenCounts(repoID int64) (issues, mrs int) {
211 s.DB.QueryRow("SELECT COUNT(*) FROM issues WHERE repo_id = ? AND state = 'open'",
212 repoID).Scan(&issues)
213 s.DB.QueryRow("SELECT COUNT(*) FROM merge_requests WHERE repo_id = ? AND state IN ('open', 'source_gone')",
214 repoID).Scan(&mrs)
215 return
216}
217
218// AssignedIssues returns open issues assigned to the user, wherever they
219// live. Assignment is a direct request for someone's attention, so it is
220// not narrowed by the involvement rule the other lists use.
221//
222// It drives from issue_assignees rather than testing EXISTS against every
223// issue: the assignee rows for one user are a handful, the issues table
224// is the whole instance.
225const assignedIssuesQuery = `
226 SELECT COALESCE(u.username, o.name) || '/' || r.name,
227 x.number, x.title, au.username, x.state, x.updated_at, 0
228 FROM issue_assignees ia
229 JOIN issues x ON x.id = ia.issue_id
230 JOIN repos r ON r.id = x.repo_id
231 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
232 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
233 JOIN users au ON au.id = x.author_id
234 WHERE ia.user_id = ?1 AND x.state = 'open'
235 ORDER BY x.updated_at DESC, x.id DESC LIMIT 20`
236
237func (s *Store) AssignedIssues(userID int64) ([]DashboardItem, error) {
238 return s.dashboardQuery(assignedIssuesQuery, userID)
239}
240
241// DashboardBuild is one build row on the dashboard, with its repo resolved.
242type DashboardBuild struct {
243 RepoPath string
244 Number int64
245 Job string
246 Status string
247 SHA string
248 Ref string
249 CreatedAt string
250 FinishedAt string
251}
252
253// RecentBuilds returns the newest builds on repositories the user can
254// reach, most recent first.
255func (s *Store) RecentBuilds(userID int64, limit int) ([]DashboardBuild, error) {
256 rows, err := s.DB.Query(`
257 SELECT COALESCE(u.username, o.name) || '/' || r.name,
258 b.number, b.job, b.status, b.sha, b.ref, b.created_at, b.finished_at
259 FROM builds b
260 JOIN repos r ON r.id = b.repo_id
261 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
262 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
263 WHERE `+reachableCond+`
264 ORDER BY b.id DESC LIMIT ?2`, userID, limit)
265 if err != nil {
266 return nil, err
267 }
268 defer rows.Close()
269 var out []DashboardBuild
270 for rows.Next() {
271 var b DashboardBuild
272 if err := rows.Scan(&b.RepoPath, &b.Number, &b.Job, &b.Status, &b.SHA, &b.Ref, &b.CreatedAt, &b.FinishedAt); err != nil {
273 return nil, err
274 }
275 out = append(out, b)
276 }
277 return out, rows.Err()
278}
279
280// FeedEvent is one line of the dashboard's activity feed.
281type FeedEvent struct {
282 ID int64
283 RepoPath string
284 Actor string
285 Kind string
286 Data string
287 CreatedAt string
288}
289
290// OwnerPublicEvents returns activity on an owner's public repositories,
291// newest first, for readers carrying no session. Push events are
292// excluded as in RecentEvents.
293func (s *Store) OwnerPublicEvents(ownerKind string, ownerID int64, limit int) ([]FeedEvent, error) {
294 return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND r.owner_kind = ? AND r.owner_id = ?
295 ORDER BY e.id DESC LIMIT ?`, ownerKind, ownerID, limit)
296}
297
298// UserPublicEvents returns what a user did on public repositories,
299// newest first. It keys on the actor, not the repository's owner, which
300// is what ActivityByDay counts for a user: the profile's log has to
301// agree with the total printed above its graph. Push events are
302// excluded as in RecentEvents.
303func (s *Store) UserPublicEvents(userID int64, limit int) ([]FeedEvent, error) {
304 return queryAll(s.DB, scanFeedEvent, feedSelect+`r.visibility = 'public' AND e.actor_id = ?
305 ORDER BY e.id DESC LIMIT ?`, userID, limit)
306}
307
308// RecentEvents returns activity on repositories the user can reach. Push
309// events are excluded: they repeat what the commit lists already show.
310// before (an event id) starts the page strictly below it, matching the
311// id-descending order; 0 starts at the newest.
312func (s *Store) RecentEvents(userID int64, limit int, before int64) ([]FeedEvent, error) {
313 q := feedSelect + reachableCond
314 args := []any{userID, limit}
315 if before > 0 {
316 q += " AND e.id < ?3"
317 args = append(args, before)
318 }
319 q += " ORDER BY e.id DESC LIMIT ?2"
320 return queryAll(s.DB, scanFeedEvent, q, args...)
321}
322
323// feedSelect reads FeedEvents, push events left out; callers append the
324// rest of the WHERE clause.
325const feedSelect = `
326 SELECT e.id, COALESCE(u.username, o.name) || '/' || r.name,
327 COALESCE(ac.username, ''), e.kind, e.data_json, e.created_at
328 FROM events e
329 JOIN repos r ON r.id = e.repo_id
330 LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
331 LEFT JOIN orgs o ON r.owner_kind = 'org' AND o.id = r.owner_id
332 LEFT JOIN users ac ON ac.id = e.actor_id
333 WHERE e.kind <> 'push' AND `
334
335func scanFeedEvent(row interface{ Scan(...any) error }) (FeedEvent, error) {
336 var e FeedEvent
337 err := row.Scan(&e.ID, &e.RepoPath, &e.Actor, &e.Kind, &e.Data, &e.CreatedAt)
338 return e, err
339}