Skip to content

Shared task board where people and AI coding agents work as teammates. Source-available, self-hostable.

Go

feat(search): implement full-text search for issues (#507)

LinYushen23136da34f2a
diff --git a/apps/web/app/(dashboard)/layout.tsx b/apps/web/app/(dashboard)/layout.tsx
index 6694f75654..ab31b92175 100644
--- a/apps/web/app/(dashboard)/layout.tsx
+++ b/apps/web/app/(dashboard)/layout.tsx
@@ -7,6 +7,7 @@ import { useNavigationStore } from "@/features/navigation";
import { SidebarProvider, SidebarInset } from "@/components/ui/sidebar";
import { useAuthStore } from "@/features/auth";
import { useWorkspaceStore } from "@/features/workspace";
+import { SearchCommand } from "@/features/search";
import { AppSidebar } from "./_components/app-sidebar";
export default function DashboardLayout({
@@ -52,6 +53,7 @@ export default function DashboardLayout({
</div>
)}
</SidebarInset>
+ <SearchCommand />
</SidebarProvider>
);
}
diff --git a/apps/web/features/search/components/search-command.tsx b/apps/web/features/search/components/search-command.tsx
new file mode 100644
index 0000000000..b7d12e4404
--- /dev/null
+++ b/apps/web/features/search/components/search-command.tsx
@@ -0,0 +1,190 @@
+"use client";
+
+import { useCallback, useEffect, useRef, useState } from "react";
+import { useRouter } from "next/navigation";
+import { Loader2, MessageSquare, SearchIcon } from "lucide-react";
+import { Command as CommandPrimitive } from "cmdk";
+import type { SearchIssueResult } from "@/shared/types";
+import { api } from "@/shared/api";
+import { StatusIcon } from "@/features/issues";
+import { STATUS_CONFIG } from "@/features/issues/config";
+import {
+ Dialog,
+ DialogContent,
+ DialogHeader,
+ DialogTitle,
+ DialogDescription,
+} from "@/components/ui/dialog";
+
+export function SearchCommand() {
+ const router = useRouter();
+ const [open, setOpen] = useState(false);
+ const [query, setQuery] = useState("");
+ const [results, setResults] = useState<SearchIssueResult[]>([]);
+ const [isLoading, setIsLoading] = useState(false);
+ const debounceRef = useRef<ReturnType<typeof setTimeout> | null>(null);
+ const abortRef = useRef<AbortController | null>(null);
+
+ // Global Cmd+K / Ctrl+K shortcut
+ useEffect(() => {
+ const handleKeyDown = (e: KeyboardEvent) => {
+ if (e.key === "k" && (e.metaKey || e.ctrlKey)) {
+ e.preventDefault();
+ setOpen((prev) => !prev);
+ }
+ };
+ document.addEventListener("keydown", handleKeyDown);
+ return () => document.removeEventListener("keydown", handleKeyDown);
+ }, []);
+
+ // Reset state when dialog closes
+ useEffect(() => {
+ if (!open) {
+ setQuery("");
+ setResults([]);
+ setIsLoading(false);
+ }
+ }, [open]);
+
+ const search = useCallback((q: string) => {
+ if (debounceRef.current) clearTimeout(debounceRef.current);
+ if (abortRef.current) abortRef.current.abort();
+
+ if (!q.trim()) {
+ setResults([]);
+ setIsLoading(false);
+ return;
+ }
+
+ setIsLoading(true);
+ debounceRef.current = setTimeout(async () => {
+ const controller = new AbortController();
+ abortRef.current = controller;
+ try {
+ const res = await api.searchIssues({
+ q: q.trim(),
+ limit: 20,
+ include_closed: true,
+ signal: controller.signal,
+ });
+ if (!controller.signal.aborted) {
+ setResults(res.issues);
+ setIsLoading(false);
+ }
+ } catch {
+ if (!controller.signal.aborted) {
+ setIsLoading(false);
+ }
+ }
+ }, 300);
+ }, []);
+
+ const handleValueChange = useCallback(
+ (value: string) => {
+ setQuery(value);
+ search(value);
+ },
+ [search],
+ );
+
+ const handleSelect = useCallback(
+ (issueId: string) => {
+ setOpen(false);
+ router.push(`/issues/${issueId}`);
+ },
+ [router],
+ );
+
+ return (
+ <Dialog open={open} onOpenChange={setOpen}>
+ <DialogHeader className="sr-only">
+ <DialogTitle>Search Issues</DialogTitle>
+ <DialogDescription>
+ Search issues by title, description, or comments
+ </DialogDescription>
+ </DialogHeader>
+ <DialogContent
+ className="top-[20%] translate-y-0 overflow-hidden rounded-xl! p-0 sm:max-w-xl!"
+ showCloseButton={false}
+ >
+ <CommandPrimitive
+ shouldFilter={false}
+ className="flex size-full flex-col overflow-hidden rounded-xl bg-popover text-popover-foreground"
+ >
+ {/* Search input */}
+ <div className="flex items-center gap-3 border-b px-4 py-3">
+ <SearchIcon className="size-5 shrink-0 text-muted-foreground" />
+ <CommandPrimitive.Input
+ placeholder="Type a command or search..."
+ value={query}
+ onValueChange={handleValueChange}
+ className="flex-1 bg-transparent text-sm outline-none placeholder:text-muted-foreground"
+ />
+ <kbd className="hidden shrink-0 rounded bg-muted px-1.5 py-0.5 text-[10px] font-medium text-muted-foreground sm:inline">
+ ESC
+ </kbd>
+ </div>
+
+ {/* Results list */}
+ <CommandPrimitive.List className="max-h-[min(400px,50vh)] overflow-y-auto overflow-x-hidden">
+ {isLoading && (
+ <div className="flex items-center justify-center py-10">
+ <Loader2 className="size-5 animate-spin text-muted-foreground" />
+ </div>
+ )}
+
+ {!isLoading && query.trim() && results.length === 0 && (
+ <CommandPrimitive.Empty className="py-10 text-center text-sm text-muted-foreground">
+ No issues found.
+ </CommandPrimitive.Empty>
+ )}
+
+ {!isLoading && results.length > 0 && (
+ <CommandPrimitive.Group className="p-2">
+ {results.map((issue) => (
+ <CommandPrimitive.Item
+ key={issue.id}
+ value={issue.id}
+ onSelect={handleSelect}
+ className="flex cursor-default select-none flex-col gap-1 rounded-lg px-3 py-2.5 text-sm outline-none data-[disabled=true]:pointer-events-none data-[disabled=true]:opacity-50 data-selected:bg-accent"
+ >
+ <div className="flex items-center gap-2.5">
+ <StatusIcon
+ status={issue.status}
+ className="size-4 shrink-0"
+ />
+ <span className="text-xs text-muted-foreground shrink-0">
+ {issue.identifier}
+ </span>
+ <span className="truncate">{issue.title}</span>
+ <span
+ className={`ml-auto text-xs shrink-0 ${STATUS_CONFIG[issue.status].iconColor}`}
+ >
+ {STATUS_CONFIG[issue.status].label}
+ </span>
+ </div>
+ {issue.match_source === "comment" &&
+ issue.matched_snippet && (
+ <div className="flex items-start gap-2 pl-[26px]">
+ <MessageSquare className="size-3 shrink-0 text-muted-foreground mt-0.5" />
+ <span className="text-xs text-muted-foreground truncate">
+ {issue.matched_snippet}
+ </span>
+ </div>
+ )}
+ </CommandPrimitive.Item>
+ ))}
+ </CommandPrimitive.Group>
+ )}
+
+ {!isLoading && !query.trim() && (
+ <div className="py-10 text-center text-sm text-muted-foreground">
+ Type to search issues...
+ </div>
+ )}
+ </CommandPrimitive.List>
+ </CommandPrimitive>
+ </DialogContent>
+ </Dialog>
+ );
+}
diff --git a/apps/web/features/search/index.ts b/apps/web/features/search/index.ts
new file mode 100644
index 0000000000..6e3baea480
--- /dev/null
+++ b/apps/web/features/search/index.ts
@@ -0,0 +1 @@
+export { SearchCommand } from "./components/search-command";
diff --git a/apps/web/shared/api/client.ts b/apps/web/shared/api/client.ts
index c5bc3d6c61..e8e6b004d7 100644
--- a/apps/web/shared/api/client.ts
+++ b/apps/web/shared/api/client.ts
@@ -3,6 +3,7 @@ import type {
CreateIssueRequest,
UpdateIssueRequest,
ListIssuesResponse,
+ SearchIssuesResponse,
UpdateMeRequest,
CreateMemberRequest,
UpdateMemberRequest,
@@ -176,6 +177,14 @@ export class ApiClient {
return this.fetch(`/api/issues?${search}`);
}
+ async searchIssues(params: { q: string; limit?: number; offset?: number; include_closed?: boolean; signal?: AbortSignal }): Promise<SearchIssuesResponse> {
+ const search = new URLSearchParams({ q: params.q });
+ if (params.limit !== undefined) search.set("limit", String(params.limit));
+ if (params.offset !== undefined) search.set("offset", String(params.offset));
+ if (params.include_closed) search.set("include_closed", "true");
+ return this.fetch(`/api/issues/search?${search}`, params.signal ? { signal: params.signal } : undefined);
+ }
+
async getIssue(id: string): Promise<Issue> {
return this.fetch(`/api/issues/${id}`);
}
diff --git a/apps/web/shared/types/api.ts b/apps/web/shared/types/api.ts
index 74e00ebbb7..dc0dca111e 100644
--- a/apps/web/shared/types/api.ts
+++ b/apps/web/shared/types/api.ts
@@ -43,6 +43,16 @@ export interface ListIssuesResponse {
doneTotal?: number;
}
+export interface SearchIssueResult extends Issue {
+ match_source: "title" | "description" | "comment";
+ matched_snippet?: string;
+}
+
+export interface SearchIssuesResponse {
+ issues: SearchIssueResult[];
+ total: number;
+}
+
export interface UpdateMeRequest {
name?: string;
avatar_url?: string;
diff --git a/server/cmd/multica/cmd_issue.go b/server/cmd/multica/cmd_issue.go
index eee480d5bd..e026e7c075 100644
--- a/server/cmd/multica/cmd_issue.go
+++ b/server/cmd/multica/cmd_issue.go
@@ -103,6 +103,13 @@ var issueRunMessagesCmd = &cobra.Command{
RunE: runIssueRunMessages,
}
+var issueSearchCmd = &cobra.Command{
+ Use: "search <query>",
+ Short: "Search issues by title or description",
+ Args: cobra.ExactArgs(1),
+ RunE: runIssueSearch,
+}
+
var validIssueStatuses = []string{
"backlog", "todo", "in_progress", "in_review", "done", "blocked", "cancelled",
}
@@ -117,6 +124,7 @@ func init() {
issueCmd.AddCommand(issueCommentCmd)
issueCmd.AddCommand(issueRunsCmd)
issueCmd.AddCommand(issueRunMessagesCmd)
+ issueCmd.AddCommand(issueSearchCmd)
issueCommentCmd.AddCommand(issueCommentListCmd)
issueCommentCmd.AddCommand(issueCommentAddCmd)
@@ -178,6 +186,11 @@ func init() {
issueCommentAddCmd.Flags().String("parent", "", "Parent comment ID (reply to a specific comment)")
issueCommentAddCmd.Flags().StringSlice("attachment", nil, "File path(s) to attach (can be specified multiple times)")
issueCommentAddCmd.Flags().String("output", "json", "Output format: table or json")
+
+ // issue search
+ issueSearchCmd.Flags().Int("limit", 20, "Maximum number of results to return")
+ issueSearchCmd.Flags().Bool("include-closed", false, "Include done and cancelled issues")
+ issueSearchCmd.Flags().String("output", "table", "Output format: table or json")
}
// ---------------------------------------------------------------------------
@@ -782,6 +795,69 @@ func runIssueRunMessages(cmd *cobra.Command, args []string) error {
return nil
}
+// ---------------------------------------------------------------------------
+// Search command
+// ---------------------------------------------------------------------------
+
+func runIssueSearch(cmd *cobra.Command, args []string) error {
+ client, err := newAPIClient(cmd)
+ if err != nil {
+ return err
+ }
+
+ ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
+ defer cancel()
+
+ params := url.Values{}
+ params.Set("q", args[0])
+ if v, _ := cmd.Flags().GetInt("limit"); v > 0 {
+ params.Set("limit", fmt.Sprintf("%d", v))
+ }
+ if v, _ := cmd.Flags().GetBool("include-closed"); v {
+ params.Set("include_closed", "true")
+ }
+
+ path := "/api/issues/search?" + params.Encode()
+
+ var result map[string]any
+ if err := client.GetJSON(ctx, path, &result); err != nil {
+ return fmt.Errorf("search issues: %w", err)
+ }
+
+ issuesRaw, _ := result["issues"].([]any)
+
+ output, _ := cmd.Flags().GetString("output")
+ if output == "json" {
+ return cli.PrintJSON(os.Stdout, result)
+ }
+
+ headers := []string{"ID", "IDENTIFIER", "TITLE", "STATUS", "MATCH"}
+ rows := make([][]string, 0, len(issuesRaw))
+ for _, raw := range issuesRaw {
+ issue, ok := raw.(map[string]any)
+ if !ok {
+ continue
+ }
+ matchInfo := strVal(issue, "match_source")
+ if snippet := strVal(issue, "matched_snippet"); snippet != "" {
+ if utf8.RuneCountInString(snippet) > 50 {
+ runes := []rune(snippet)
+ snippet = string(runes[:47]) + "..."
+ }
+ matchInfo += ": " + snippet
+ }
+ rows = append(rows, []string{
+ truncateID(strVal(issue, "id")),
+ strVal(issue, "identifier"),
+ strVal(issue, "title"),
+ strVal(issue, "status"),
+ matchInfo,
+ })
+ }
+ cli.PrintTable(os.Stdout, headers, rows)
+ return nil
+}
+
// ---------------------------------------------------------------------------
// Helpers
// ---------------------------------------------------------------------------
diff --git a/server/cmd/server/router.go b/server/cmd/server/router.go
index 1d9fe8d7d2..3fa7c240e3 100644
--- a/server/cmd/server/router.go
+++ b/server/cmd/server/router.go
@@ -157,6 +157,7 @@ func NewRouter(pool *pgxpool.Pool, hub *realtime.Hub, bus *events.Bus) chi.Route
// Issues
r.Route("/api/issues", func(r chi.Router) {
+ r.Get("/search", h.SearchIssues)
r.Get("/", h.ListIssues)
r.Post("/", h.CreateIssue)
r.Post("/batch-update", h.BatchUpdateIssues)
diff --git a/server/internal/handler/issue.go b/server/internal/handler/issue.go
index 933ba64ef6..2affdb36bf 100644
--- a/server/internal/handler/issue.go
+++ b/server/internal/handler/issue.go
@@ -7,6 +7,7 @@ import (
"log/slog"
"net/http"
"strconv"
+ "strings"
"time"
"github.com/go-chi/chi/v5"
@@ -62,6 +63,145 @@ func issueToResponse(i db.Issue, issuePrefix string) IssueResponse {
}
}
+// SearchIssueResponse extends IssueResponse with search metadata.
+type SearchIssueResponse struct {
+ IssueResponse
+ MatchSource string `json:"match_source"`
+ MatchedSnippet *string `json:"matched_snippet,omitempty"`
+}
+
+// extractSnippet extracts a snippet of text around the first occurrence of query.
+// Returns up to ~120 chars centered on the match.
+func extractSnippet(content, query string) string {
+ lower := strings.ToLower(content)
+ idx := strings.Index(lower, strings.ToLower(query))
+ if idx < 0 {
+ if len(content) > 120 {
+ return content[:120] + "..."
+ }
+ return content
+ }
+ start := idx - 40
+ if start < 0 {
+ start = 0
+ }
+ end := idx + len(query) + 80
+ if end > len(content) {
+ end = len(content)
+ }
+ snippet := content[start:end]
+ if start > 0 {
+ snippet = "..." + snippet
+ }
+ if end < len(content) {
+ snippet = snippet + "..."
+ }
+ return snippet
+}
+
+// escapeLike escapes LIKE special characters (%, _, \) in user input.
+func escapeLike(s string) string {
+ s = strings.ReplaceAll(s, `\`, `\\`)
+ s = strings.ReplaceAll(s, `%`, `\%`)
+ s = strings.ReplaceAll(s, `_`, `\_`)
+ return s
+}
+
+func (h *Handler) SearchIssues(w http.ResponseWriter, r *http.Request) {
+ ctx := r.Context()
+ workspaceID := resolveWorkspaceID(r)
+
+ q := r.URL.Query().Get("q")
+ if q == "" {
+ writeError(w, http.StatusBadRequest, "q parameter is required")
+ return
+ }
+
+ limit := 20
+ offset := 0
+ if l := r.URL.Query().Get("limit"); l != "" {
+ if v, err := strconv.Atoi(l); err == nil && v > 0 {
+ limit = v
+ }
+ }
+ if limit > 50 {
+ limit = 50
+ }
+ if o := r.URL.Query().Get("offset"); o != "" {
+ if v, err := strconv.Atoi(o); err == nil && v >= 0 {
+ offset = v
+ }
+ }
+
+ includeClosed := r.URL.Query().Get("include_closed") == "true"
+
+ wsUUID := parseUUID(workspaceID)
+ queryText := strToText(escapeLike(q))
+
+ rows, err := h.Queries.SearchIssues(ctx, db.SearchIssuesParams{
+ WorkspaceID: wsUUID,
+ Query: queryText,
+ SearchLimit: int32(limit),
+ SearchOffset: int32(offset),
+ IncludeClosed: includeClosed,
+ })
+ if err != nil {
+ slog.Warn("search issues failed", "error", err, "workspace_id", workspaceID, "query", q)
+ writeError(w, http.StatusInternalServerError, "failed to search issues")
+ return
+ }
+
+ var total int64
+ if len(rows) > 0 {
+ total = rows[0].TotalCount
+ }
+
+ prefix := h.getIssuePrefix(ctx, wsUUID)
+ resp := make([]SearchIssueResponse, len(rows))
+ for i, row := range rows {
+ sir := SearchIssueResponse{
+ IssueResponse: issueToResponse(searchRowToIssue(row), prefix),
+ MatchSource: row.MatchSource,
+ }
+ if row.MatchSource == "comment" {
+ if content, ok := row.MatchedCommentContent.(string); ok && content != "" {
+ snippet := extractSnippet(content, q)
+ sir.MatchedSnippet = &snippet
+ }
+ }
+ resp[i] = sir
+ }
+
+ w.Header().Set("X-Total-Count", strconv.FormatInt(total, 10))
+ writeJSON(w, http.StatusOK, map[string]any{
+ "issues": resp,
+ "total": total,
+ })
+}
+
+func searchRowToIssue(row db.SearchIssuesRow) db.Issue {
+ return db.Issue{
+ ID: row.ID,
+ WorkspaceID: row.WorkspaceID,
+ Title: row.Title,
+ Description: row.Description,
+ Status: row.Status,
+ Priority: row.Priority,
+ AssigneeType: row.AssigneeType,
+ AssigneeID: row.AssigneeID,
+ CreatorType: row.CreatorType,
+ CreatorID: row.CreatorID,
+ ParentIssueID: row.ParentIssueID,
+ AcceptanceCriteria: row.AcceptanceCriteria,
+ ContextRefs: row.ContextRefs,
+ Position: row.Position,
+ DueDate: row.DueDate,
+ CreatedAt: row.CreatedAt,
+ UpdatedAt: row.UpdatedAt,
+ Number: row.Number,
+ }
+}
+
func (h *Handler) ListIssues(w http.ResponseWriter, r *http.Request) {
ctx := r.Context()
diff --git a/server/migrations/032_issue_search_index.down.sql b/server/migrations/032_issue_search_index.down.sql
new file mode 100644
index 0000000000..05bd362366
--- /dev/null
+++ b/server/migrations/032_issue_search_index.down.sql
@@ -0,0 +1,3 @@
+DROP INDEX IF EXISTS idx_issue_description_bigm;
+DROP INDEX IF EXISTS idx_issue_title_bigm;
+DROP EXTENSION IF EXISTS pg_bigm;
diff --git a/server/migrations/032_issue_search_index.up.sql b/server/migrations/032_issue_search_index.up.sql
new file mode 100644
index 0000000000..bda9d2cfe5
--- /dev/null
+++ b/server/migrations/032_issue_search_index.up.sql
@@ -0,0 +1,8 @@
+-- Enable pg_bigm extension for bigram-based full-text search (CJK-friendly).
+CREATE EXTENSION IF NOT EXISTS pg_bigm;
+
+-- GIN index on issue title for LIKE '%keyword%' queries.
+CREATE INDEX idx_issue_title_bigm ON issue USING gin (title gin_bigm_ops);
+
+-- GIN index on issue description (nullable, use COALESCE).
+CREATE INDEX idx_issue_description_bigm ON issue USING gin (COALESCE(description, '') gin_bigm_ops);
diff --git a/server/migrations/033_comment_search_index.down.sql b/server/migrations/033_comment_search_index.down.sql
new file mode 100644
index 0000000000..abc79dafed
--- /dev/null
+++ b/server/migrations/033_comment_search_index.down.sql
@@ -0,0 +1 @@
+DROP INDEX IF EXISTS idx_comment_content_bigm;
diff --git a/server/migrations/033_comment_search_index.up.sql b/server/migrations/033_comment_search_index.up.sql
new file mode 100644
index 0000000000..b552fde38f
--- /dev/null
+++ b/server/migrations/033_comment_search_index.up.sql
@@ -0,0 +1,2 @@
+-- GIN index on comment content for LIKE '%keyword%' queries (pg_bigm).
+CREATE INDEX idx_comment_content_bigm ON comment USING gin (content gin_bigm_ops);
diff --git a/server/pkg/db/generated/issue.sql.go b/server/pkg/db/generated/issue.sql.go
index c9504c2712..d0946bb5c1 100644
--- a/server/pkg/db/generated/issue.sql.go
+++ b/server/pkg/db/generated/issue.sql.go
@@ -380,6 +380,125 @@ func (q *Queries) ListOpenIssues(ctx context.Context, arg ListOpenIssuesParams)
return items, nil
}
+const searchIssues = `-- name: SearchIssues :many
+SELECT i.id, i.workspace_id, i.title, i.description, i.status, i.priority, i.assignee_type, i.assignee_id, i.creator_type, i.creator_id, i.parent_issue_id, i.acceptance_criteria, i.context_refs, i.position, i.due_date, i.created_at, i.updated_at, i.number,
+ COUNT(*) OVER() AS total_count,
+ CASE
+ WHEN i.title LIKE '%' || $1 || '%' THEN 'title'
+ WHEN COALESCE(i.description, '') LIKE '%' || $1 || '%' THEN 'description'
+ ELSE 'comment'
+ END AS match_source,
+ CASE
+ WHEN i.title LIKE '%' || $1 || '%' THEN ''
+ WHEN COALESCE(i.description, '') LIKE '%' || $1 || '%' THEN ''
+ ELSE COALESCE(
+ (SELECT c.content FROM comment c
+ WHERE c.issue_id = i.id AND c.content LIKE '%' || $1 || '%'
+ ORDER BY c.created_at DESC LIMIT 1),
+ ''
+ )
+ END AS matched_comment_content
+FROM issue i
+WHERE i.workspace_id = $2
+ AND (
+ i.title LIKE '%' || $1 || '%'
+ OR COALESCE(i.description, '') LIKE '%' || $1 || '%'
+ OR EXISTS (
+ SELECT 1 FROM comment c
+ WHERE c.issue_id = i.id AND c.content LIKE '%' || $1 || '%'
+ )
+ )
+ AND ($3::boolean OR i.status NOT IN ('done', 'cancelled'))
+ORDER BY
+ CASE
+ WHEN i.title LIKE '%' || $1 || '%' THEN 0
+ WHEN COALESCE(i.description, '') LIKE '%' || $1 || '%' THEN 1
+ ELSE 2
+ END,
+ i.updated_at DESC
+LIMIT $5 OFFSET $4
+`
+
+type SearchIssuesParams struct {
+ Query pgtype.Text `json:"query"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ IncludeClosed bool `json:"include_closed"`
+ SearchOffset int32 `json:"search_offset"`
+ SearchLimit int32 `json:"search_limit"`
+}
+
+type SearchIssuesRow struct {
+ ID pgtype.UUID `json:"id"`
+ WorkspaceID pgtype.UUID `json:"workspace_id"`
+ Title string `json:"title"`
+ Description pgtype.Text `json:"description"`
+ Status string `json:"status"`
+ Priority string `json:"priority"`
+ AssigneeType pgtype.Text `json:"assignee_type"`
+ AssigneeID pgtype.UUID `json:"assignee_id"`
+ CreatorType string `json:"creator_type"`
+ CreatorID pgtype.UUID `json:"creator_id"`
+ ParentIssueID pgtype.UUID `json:"parent_issue_id"`
+ AcceptanceCriteria []byte `json:"acceptance_criteria"`
+ ContextRefs []byte `json:"context_refs"`
+ Position float64 `json:"position"`
+ DueDate pgtype.Timestamptz `json:"due_date"`
+ CreatedAt pgtype.Timestamptz `json:"created_at"`
+ UpdatedAt pgtype.Timestamptz `json:"updated_at"`
+ Number int32 `json:"number"`
+ TotalCount int64 `json:"total_count"`
+ MatchSource string `json:"match_source"`
+ MatchedCommentContent interface{} `json:"matched_comment_content"`
+}
+
+func (q *Queries) SearchIssues(ctx context.Context, arg SearchIssuesParams) ([]SearchIssuesRow, error) {
+ rows, err := q.db.Query(ctx, searchIssues,
+ arg.Query,
+ arg.WorkspaceID,
+ arg.IncludeClosed,
+ arg.SearchOffset,
+ arg.SearchLimit,
+ )
+ if err != nil {
+ return nil, err
+ }
+ defer rows.Close()
+ items := []SearchIssuesRow{}
+ for rows.Next() {
+ var i SearchIssuesRow
+ if err := rows.Scan(
+ &i.ID,
+ &i.WorkspaceID,
+ &i.Title,
+ &i.Description,
+ &i.Status,
+ &i.Priority,
+ &i.AssigneeType,
+ &i.AssigneeID,
+ &i.CreatorType,
+ &i.CreatorID,
+ &i.ParentIssueID,
+ &i.AcceptanceCriteria,
+ &i.ContextRefs,
+ &i.Position,
+ &i.DueDate,
+ &i.CreatedAt,
+ &i.UpdatedAt,
+ &i.Number,
+ &i.TotalCount,
+ &i.MatchSource,
+ &i.MatchedCommentContent,
+ ); err != nil {
+ return nil, err
+ }
+ items = append(items, i)
+ }
+ if err := rows.Err(); err != nil {
+ return nil, err
+ }
+ return items, nil
+}
+
const updateIssue = `-- name: UpdateIssue :one
UPDATE issue SET
title = COALESCE($2, title),
diff --git a/server/pkg/db/queries/issue.sql b/server/pkg/db/queries/issue.sql
index 571d54bfce..c98132a6db 100644
--- a/server/pkg/db/queries/issue.sql
+++ b/server/pkg/db/queries/issue.sql
@@ -72,3 +72,41 @@ WHERE workspace_id = $1
SELECT * FROM issue
WHERE parent_issue_id = $1
ORDER BY position ASC, created_at DESC;
+
+-- name: SearchIssues :many
+SELECT i.*,
+ COUNT(*) OVER() AS total_count,
+ CASE
+ WHEN i.title LIKE '%' || @query || '%' THEN 'title'
+ WHEN COALESCE(i.description, '') LIKE '%' || @query || '%' THEN 'description'
+ ELSE 'comment'
+ END AS match_source,
+ CASE
+ WHEN i.title LIKE '%' || @query || '%' THEN ''
+ WHEN COALESCE(i.description, '') LIKE '%' || @query || '%' THEN ''
+ ELSE COALESCE(
+ (SELECT c.content FROM comment c
+ WHERE c.issue_id = i.id AND c.content LIKE '%' || @query || '%'
+ ORDER BY c.created_at DESC LIMIT 1),
+ ''
+ )
+ END AS matched_comment_content
+FROM issue i
+WHERE i.workspace_id = @workspace_id
+ AND (
+ i.title LIKE '%' || @query || '%'
+ OR COALESCE(i.description, '') LIKE '%' || @query || '%'
+ OR EXISTS (
+ SELECT 1 FROM comment c
+ WHERE c.issue_id = i.id AND c.content LIKE '%' || @query || '%'
+ )
+ )
+ AND (@include_closed::boolean OR i.status NOT IN ('done', 'cancelled'))
+ORDER BY
+ CASE
+ WHEN i.title LIKE '%' || @query || '%' THEN 0
+ WHEN COALESCE(i.description, '') LIKE '%' || @query || '%' THEN 1
+ ELSE 2
+ END,
+ i.updated_at DESC
+LIMIT @search_limit OFFSET @search_offset;