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