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.

62 lines
1.0 KiB

  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, "\"") {
  15. if len(token) > 1 {
  16. token = token[1:]
  17. }
  18. startQuotes = true
  19. }
  20. if strings.HasSuffix(token, "\"") {
  21. token = token[:len(token)-1]
  22. startQuotes = false
  23. clearQuotes = true
  24. }
  25. token := strings.Trim(token, ",.;:()\"")
  26. if len(token) > 0 {
  27. if startQuotes {
  28. if i > 0 {
  29. result += " & "
  30. }
  31. result += "("
  32. } else if inQuotes {
  33. result += "<->"
  34. } else if i != 0 {
  35. result += " & "
  36. }
  37. result += token
  38. }
  39. if startQuotes {
  40. inQuotes = true
  41. }
  42. if clearQuotes {
  43. inQuotes = false
  44. result += ")"
  45. }
  46. }
  47. if inQuotes {
  48. return result
  49. }
  50. return strings.TrimLeft(result, " ")
  51. }