builder.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. if pg {
  39. out = append(out, tagv)
  40. } else {
  41. out = append(out, fmt.Sprintf("`%s`", tagv))
  42. }
  43. }
  44. }
  45. return out
  46. }
  47. // PostgreSqlJoin concatenates the given elements into a string.
  48. func PostgreSqlJoin(elems []string) string {
  49. b := new(strings.Builder)
  50. for index, e := range elems {
  51. b.WriteString(fmt.Sprintf("%s = $%d, ", e, index+2))
  52. }
  53. if b.Len() == 0 {
  54. return b.String()
  55. }
  56. return b.String()[0 : b.Len()-2]
  57. }