builder.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package builderx
  2. import (
  3. "fmt"
  4. "reflect"
  5. "github.com/go-xorm/builder"
  6. )
  7. const dbTag = "db"
  8. // NewEq wraps builder.Eq
  9. func NewEq(in interface{}) builder.Eq {
  10. return builder.Eq(ToMap(in))
  11. }
  12. // NewGt wraps builder.Gt
  13. func NewGt(in interface{}) builder.Gt {
  14. return builder.Gt(ToMap(in))
  15. }
  16. // ToMap converts interface into map
  17. func ToMap(in interface{}) map[string]interface{} {
  18. out := make(map[string]interface{})
  19. v := reflect.ValueOf(in)
  20. if v.Kind() == reflect.Ptr {
  21. v = v.Elem()
  22. }
  23. // we only accept structs
  24. if v.Kind() != reflect.Struct {
  25. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  26. }
  27. typ := v.Type()
  28. for i := 0; i < v.NumField(); i++ {
  29. // gets us a StructField
  30. fi := typ.Field(i)
  31. if tagv := fi.Tag.Get(dbTag); tagv != "" {
  32. // set key of map to value in struct field
  33. val := v.Field(i)
  34. zero := reflect.Zero(val.Type()).Interface()
  35. current := val.Interface()
  36. if reflect.DeepEqual(current, zero) {
  37. continue
  38. }
  39. out[tagv] = current
  40. }
  41. }
  42. return out
  43. }
  44. // deprecated: use RawFieldNames instead automatically while model generating after goctl version v1.1.0
  45. func FieldNames(in interface{}) []string {
  46. out := make([]string, 0)
  47. v := reflect.ValueOf(in)
  48. if v.Kind() == reflect.Ptr {
  49. v = v.Elem()
  50. }
  51. // we only accept structs
  52. if v.Kind() != reflect.Struct {
  53. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  54. }
  55. typ := v.Type()
  56. for i := 0; i < v.NumField(); i++ {
  57. // gets us a StructField
  58. fi := typ.Field(i)
  59. if tagv := fi.Tag.Get(dbTag); tagv != "" {
  60. out = append(out, tagv)
  61. } else {
  62. out = append(out, fi.Name)
  63. }
  64. }
  65. return out
  66. }
  67. // RawFieldNames converts golang struct field into slice string
  68. func RawFieldNames(in interface{}) []string {
  69. out := make([]string, 0)
  70. v := reflect.ValueOf(in)
  71. if v.Kind() == reflect.Ptr {
  72. v = v.Elem()
  73. }
  74. // we only accept structs
  75. if v.Kind() != reflect.Struct {
  76. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  77. }
  78. typ := v.Type()
  79. for i := 0; i < v.NumField(); i++ {
  80. // gets us a StructField
  81. fi := typ.Field(i)
  82. if tagv := fi.Tag.Get(dbTag); tagv != "" {
  83. out = append(out, fmt.Sprintf("`%s`", tagv))
  84. } else {
  85. out = append(out, fmt.Sprintf(`"%s"`, fi.Name))
  86. }
  87. }
  88. return out
  89. }