You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

search.rb 1.4KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. require 'sequel'
  2. def search(params)
  3. db = Sequel.connect(adapter: :postgres, database: ENV['DB_DATABASE'])
  4. query = params[:q].strip
  5. offset = (params[:page] - 1) * 10
  6. username = params[:username].strip
  7. case params[:type]
  8. when 'threads'
  9. sort =
  10. case params[:sort]
  11. when 'thread'
  12. 'threads.created_at DESC'
  13. when 'post'
  14. 'posts.created_at DESC'
  15. else
  16. 'threads.created_at DESC'
  17. end
  18. search_threads(db, query, username, sort, offset)
  19. when 'posts'
  20. search_posts(db, query, username, offset)
  21. else
  22. Array.new
  23. end
  24. end
  25. def search_threads(db, query, username, sort, offset)
  26. db[<<-SQL, query, username, username, String.new, offset]
  27. SELECT
  28. threads.*
  29. FROM threads
  30. WHERE
  31. to_tsvector(title) @@ plainto_tsquery(?)
  32. AND (LOWER(threads.creator) = LOWER(?) OR ? = '')
  33. ORDER BY #{sort}
  34. LIMIT 10
  35. OFFSET ?;
  36. SQL
  37. end
  38. def search_posts(db, query, username, offset)
  39. db[<<-SQL, query, username, username, offset]
  40. SELECT
  41. posts.*,
  42. threads.title as thread_title,
  43. threads.remote_id as remote_thread_id
  44. FROM posts
  45. INNER JOIN threads on posts.thread_id = threads.id
  46. WHERE
  47. to_tsvector(body) @@ plainto_tsquery(?)
  48. AND (
  49. (LOWER(posts.creator) = LOWER(?)) OR (? = '')
  50. )
  51. ORDER BY created_at DESC
  52. LIMIT 10
  53. OFFSET ?;
  54. SQL
  55. end