package store import ( "context" "fmt" "github.com/jackc/pgx/v5/pgxpool" ) const suggestLimit = 10 // SuggestStore provides autocomplete search over aggregated item names. type SuggestStore struct { pool *pgxpool.Pool } // NewSuggestStore creates a SuggestStore backed by the given pool. func NewSuggestStore(pool *pgxpool.Pool) *SuggestStore { return &SuggestStore{pool: pool} } // Search returns up to suggestLimit item name suggestions matching q using // pg_trgm similarity search. Results are ordered by usage_count DESC so the // most-used names appear first. func (s *SuggestStore) Search(ctx context.Context, q string) ([]string, error) { rows, err := s.pool.Query(ctx, ` SELECT name FROM item_names WHERE name % $1 OR name LIKE $2 ORDER BY usage_count DESC, last_used_at DESC LIMIT $3`, q, q+"%", suggestLimit, ) if err != nil { return nil, fmt.Errorf("suggeststore: search: %w", err) } defer rows.Close() var names []string for rows.Next() { var name string if err := rows.Scan(&name); err != nil { return nil, fmt.Errorf("suggeststore: scan name: %w", err) } names = append(names, name) } return names, rows.Err() }