package content import ( "strings" "supermarket/internal/db" ) // matchAll builds a condition that every word appears in one of the columns // (case-insensitively for ASCII, as SQLite's lower() is), and its arguments. // Words are expected in lower case. func matchAll(words []string, columns ...string) (string, []any) { hay := "lower(" + strings.Join(columns, " || ' ' || ") + ")" conds := make([]string, 0, len(words)) args := make([]any, 0, len(words)) for _, w := range words { conds = append(conds, "instr("+hay+", ?) > 0") args = append(args, w) } return strings.Join(conds, " AND "), args } // SearchItems returns fetched items (dismissed ones too) containing every // word, newest first. Products, which are in the profile, are left out. func SearchItems(d *db.DB, words []string, limit int) ([]Item, error) { if len(words) == 0 { return nil, nil } cond, args := matchAll(words, "c.title", "c.body", "c.author", "c.author_handle", "c.url") rows, err := d.Query(`SELECT `+itemColumns+itemFrom+` WHERE c.source != 'Product' AND `+cond+` ORDER BY c.published_at DESC LIMIT ?`, append(args, limit)...) if err != nil { return nil, err } return scanItems(rows) } // SearchDrafts returns posts (not discarded ones) containing every word, // most recently changed first. func SearchDrafts(d *db.DB, words []string, limit int) ([]Draft, error) { if len(words) == 0 { return nil, nil } cond, args := matchAll(words, "content", "title", "target", "inventory_name", "source_url") rows, err := d.Query(`SELECT `+draftColumns+` FROM drafts WHERE status != ? AND `+cond+` ORDER BY updated_at DESC, id DESC LIMIT ?`, append(append([]any{StatusDiscarded}, args...), limit)...) if err != nil { return nil, err } return scanDrafts(rows) }