builder.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package builder
  2. import (
  3. "fmt"
  4. "reflect"
  5. "strings"
  6. )
  7. const dbTag = "db"
  8. // RawFieldNames converts golang struct field into slice string.
  9. func RawFieldNames(in interface{}, postgresSql ...bool) []string {
  10. out := make([]string, 0)
  11. v := reflect.ValueOf(in)
  12. if v.Kind() == reflect.Ptr {
  13. v = v.Elem()
  14. }
  15. var pg bool
  16. if len(postgresSql) > 0 {
  17. pg = postgresSql[0]
  18. }
  19. // we only accept structs
  20. if v.Kind() != reflect.Struct {
  21. panic(fmt.Errorf("ToMap only accepts structs; got %T", v))
  22. }
  23. typ := v.Type()
  24. for i := 0; i < v.NumField(); i++ {
  25. // gets us a StructField
  26. fi := typ.Field(i)
  27. tagv := fi.Tag.Get(dbTag)
  28. switch tagv {
  29. case "-":
  30. continue
  31. case "":
  32. if pg {
  33. out = append(out, fi.Name)
  34. } else {
  35. out = append(out, fmt.Sprintf("`%s`", fi.Name))
  36. }
  37. default:
  38. //get tag name with the tag opton, e.g.:
  39. //`db:"id"`
  40. //`db:"id,type=char,length=16"`
  41. //`db:",type=char,length=16"`
  42. if strings.Contains(tagv, ",") {
  43. tagv = strings.TrimSpace(strings.Split(tagv, ",")[0])
  44. }
  45. if tagv != "" {
  46. if pg {
  47. out = append(out, tagv)
  48. } else {
  49. out = append(out, fmt.Sprintf("`%s`", tagv))
  50. }
  51. } else {
  52. if pg {
  53. out = append(out, fi.Name)
  54. } else {
  55. out = append(out, fmt.Sprintf("`%s`", fi.Name))
  56. }
  57. }
  58. }
  59. }
  60. return out
  61. }
  62. // PostgreSqlJoin concatenates the given elements into a string.
  63. func PostgreSqlJoin(elems []string) string {
  64. b := new(strings.Builder)
  65. for index, e := range elems {
  66. b.WriteString(fmt.Sprintf("%s = $%d, ", e, index+2))
  67. }
  68. if b.Len() == 0 {
  69. return b.String()
  70. }
  71. return b.String()[0 : b.Len()-2]
  72. }