builder.go 2.0 KB

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