github.com/shuguocloud/go-zero@v1.3.0/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  		if tagv := fi.Tag.Get(dbTag); tagv != "" {
    34  			if pg {
    35  				out = append(out, tagv)
    36  			} else {
    37  				out = append(out, fmt.Sprintf("`%s`", tagv))
    38  			}
    39  		} else {
    40  			if pg {
    41  				out = append(out, fi.Name)
    42  			} else {
    43  				out = append(out, fmt.Sprintf("`%s`", fi.Name))
    44  			}
    45  		}
    46  	}
    47  
    48  	return out
    49  }
    50  
    51  // PostgreSqlJoin concatenates the given elements into a string.
    52  func PostgreSqlJoin(elems []string) string {
    53  	b := new(strings.Builder)
    54  	for index, e := range elems {
    55  		b.WriteString(fmt.Sprintf("%s = $%d, ", e, index+2))
    56  	}
    57  
    58  	if b.Len() == 0 {
    59  		return b.String()
    60  	}
    61  
    62  	return b.String()[0 : b.Len()-2]
    63  }