builder.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108
  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. // FieldNames returns field names from given in.
  45. // deprecated: use RawFieldNames instead automatically while model generating after goctl version v1.1.0
  46. func FieldNames(in interface{}) []string {
  47. out := make([]string, 0)
  48. v := reflect.ValueOf(in)
  49. if v.Kind() == reflect.Ptr {
  50. v = v.Elem()
  51. }
  52. // we only accept structs
  53. if v.Kind() != reflect.Struct {
  54. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  55. }
  56. typ := v.Type()
  57. for i := 0; i < v.NumField(); i++ {
  58. // gets us a StructField
  59. fi := typ.Field(i)
  60. if tagv := fi.Tag.Get(dbTag); tagv != "" {
  61. out = append(out, tagv)
  62. } else {
  63. out = append(out, fi.Name)
  64. }
  65. }
  66. return out
  67. }
  68. // RawFieldNames converts golang struct field into slice string
  69. func RawFieldNames(in interface{}) []string {
  70. out := make([]string, 0)
  71. v := reflect.ValueOf(in)
  72. if v.Kind() == reflect.Ptr {
  73. v = v.Elem()
  74. }
  75. // we only accept structs
  76. if v.Kind() != reflect.Struct {
  77. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  78. }
  79. typ := v.Type()
  80. for i := 0; i < v.NumField(); i++ {
  81. // gets us a StructField
  82. fi := typ.Field(i)
  83. if tagv := fi.Tag.Get(dbTag); tagv != "" {
  84. out = append(out, fmt.Sprintf("`%s`", tagv))
  85. } else {
  86. out = append(out, fmt.Sprintf(`"%s"`, fi.Name))
  87. }
  88. }
  89. return out
  90. }