whereBuild.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788
  1. package utils
  2. import (
  3. "fmt"
  4. "strings"
  5. )
  6. type NullType byte
  7. const (
  8. _ NullType = iota
  9. // IsNull the same as `is null`
  10. IsNull
  11. // IsNotNull the same as `is not null`
  12. IsNotNull
  13. )
  14. // sql生成工具
  15. func WhereBuild(where map[string]interface{}) (whereSQL string, vals []interface{}, err error) {
  16. for k, v := range where {
  17. ks := strings.Split(k, " ")
  18. if len(ks) > 2 {
  19. return "", nil, fmt.Errorf("Error in query condition: %s. ", k)
  20. }
  21. if whereSQL != "" {
  22. whereSQL += " AND "
  23. }
  24. strings.Join(ks, ",")
  25. switch len(ks) {
  26. case 1:
  27. //fmt.Println(reflect.TypeOf(v))
  28. switch v := v.(type) {
  29. case NullType:
  30. if v == IsNotNull {
  31. whereSQL += fmt.Sprint(k, " IS NOT NULL")
  32. } else {
  33. whereSQL += fmt.Sprint(k, " IS NULL")
  34. }
  35. default:
  36. whereSQL += fmt.Sprint(k, "=?")
  37. vals = append(vals, v)
  38. }
  39. break
  40. case 2:
  41. k = ks[0]
  42. switch ks[1] {
  43. case "=":
  44. whereSQL += fmt.Sprint(k, "=?")
  45. vals = append(vals, v)
  46. break
  47. case ">":
  48. whereSQL += fmt.Sprint(k, ">?")
  49. vals = append(vals, v)
  50. break
  51. case ">=":
  52. whereSQL += fmt.Sprint(k, ">=?")
  53. vals = append(vals, v)
  54. break
  55. case "<":
  56. whereSQL += fmt.Sprint(k, "<?")
  57. vals = append(vals, v)
  58. break
  59. case "<=":
  60. whereSQL += fmt.Sprint(k, "<=?")
  61. vals = append(vals, v)
  62. break
  63. case "!=":
  64. whereSQL += fmt.Sprint(k, "!=?")
  65. vals = append(vals, v)
  66. break
  67. case "<>":
  68. whereSQL += fmt.Sprint(k, "!=?")
  69. vals = append(vals, v)
  70. break
  71. case "in":
  72. whereSQL += fmt.Sprint(k, " in (?)")
  73. vals = append(vals, v)
  74. break
  75. case "like":
  76. whereSQL += fmt.Sprint(k, " like ?")
  77. vals = append(vals, v)
  78. }
  79. break
  80. }
  81. }
  82. return
  83. }