internal/store/search.go

53 lines · 2095 bytes

 1package store
 2
 3// Search across repositories, for the `search` command and the web's
 4// /search page. Visibility is the same rule everywhere: public plus what
 5// the user reaches, so an anonymous caller (user id 0) sees only public
 6// rows rather than a different query.
 7
 8// visibleCond admits public repositories and anything the user reaches.
 9const visibleCond = `(r.visibility = 'public' OR ` + reachableCond + `)`
10
11// VisibleRepos returns every repository the user may read, public ones
12// included, ordered by owner then name.
13func (s *Store) VisibleRepos(userID int64) ([]Repo, error) {
14	return queryAll(s.DB, scanRepo, repoSelect+" WHERE "+visibleCond+" ORDER BY 4, r.name", userID)
15}
16
17// SearchIssues returns issues matching q in title or body, newest
18// activity first.
19func (s *Store) SearchIssues(userID int64, q string, limit int) ([]DashboardItem, error) {
20	return s.searchQuery("issues", "issue_fts", userID, q, limit)
21}
22
23// SearchMRs is SearchIssues for merge requests.
24func (s *Store) SearchMRs(userID int64, q string, limit int) ([]DashboardItem, error) {
25	return s.searchQuery("merge_requests", "mr_fts", userID, q, limit)
26}
27
28func (s *Store) searchQuery(table, index string, userID int64, q string, limit int) ([]DashboardItem, error) {
29	rows, err := s.DB.Query(`
30		SELECT COALESCE(u.username, o.name) || '/' || r.name,
31		       x.number, x.title, au.username, x.state, x.updated_at
32		FROM `+table+` x
33		JOIN repos r ON r.id = x.repo_id
34		LEFT JOIN users u ON r.owner_kind = 'user' AND u.id = r.owner_id
35		LEFT JOIN orgs o  ON r.owner_kind = 'org'  AND o.id = r.owner_id
36		JOIN users au ON au.id = x.author_id
37		WHERE x.id IN (SELECT rowid FROM `+index+` WHERE `+index+` MATCH ?2)
38		  AND `+visibleCond+`
39		ORDER BY x.updated_at DESC LIMIT ?3`, userID, FTSQuery(q), limit)
40	if err != nil {
41		return nil, err
42	}
43	defer rows.Close()
44	var out []DashboardItem
45	for rows.Next() {
46		var d DashboardItem
47		if err := rows.Scan(&d.RepoPath, &d.Number, &d.Title, &d.Author, &d.State, &d.UpdatedAt); err != nil {
48			return nil, err
49		}
50		out = append(out, d)
51	}
52	return out, rows.Err()
53}