GraphQL API and utilities for the rpdata project
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.

61 lines
1011 B

  1. package postgres
  2. import "strings"
  3. // TSQueryFromSearch generates a TS query from a typical search string.
  4. func TSQueryFromSearch(search string) string {
  5. if strings.HasPrefix(search, "tsq:") {
  6. return search[4:]
  7. }
  8. tokens := strings.Split(search, " ")
  9. inQuotes := false
  10. result := ""
  11. for i, token := range tokens {
  12. clearQuotes := false
  13. startQuotes := false
  14. if strings.HasPrefix(token, "\"") && len(token) > 1 {
  15. startQuotes = true
  16. }
  17. if strings.HasSuffix(token, "\"") {
  18. if !startQuotes {
  19. clearQuotes = true
  20. }
  21. startQuotes = false
  22. }
  23. token := strings.Trim(token, ",.;:()\"")
  24. if len(token) > 0 {
  25. if startQuotes {
  26. if i > 0 {
  27. result += " & "
  28. }
  29. result += "("
  30. } else if inQuotes {
  31. result += "<->"
  32. } else if i != 0 {
  33. result += " & "
  34. }
  35. result += token
  36. }
  37. if startQuotes {
  38. inQuotes = true
  39. }
  40. if clearQuotes {
  41. inQuotes = false
  42. result += ")"
  43. }
  44. }
  45. if inQuotes {
  46. return result
  47. }
  48. return strings.TrimLeft(result, " ")
  49. }