diff --git a/sql.go b/sql.go index 2235bb28..67f6b60a 100644 --- a/sql.go +++ b/sql.go @@ -51,7 +51,7 @@ func (s *Orm) query(out interface{}) { columns, _ := rows.Columns() var values []interface{} for _, value := range columns { - values = append(values, dest.FieldByName(value).Addr().Interface()) + values = append(values, dest.FieldByName(snakeToUpperCamel(value)).Addr().Interface()) } s.Error = rows.Scan(values...) } diff --git a/utils.go b/utils.go index 96e6dbbb..6aca31b5 100644 --- a/utils.go +++ b/utils.go @@ -1,6 +1,7 @@ package gorm import ( + "bytes" "fmt" "reflect" "strings" @@ -12,7 +13,7 @@ func modelValues(m interface{}) (columns []string, values []interface{}) { for i := 0; i < typ.NumField(); i++ { p := typ.Field(i) if !p.Anonymous { - columns = append(columns, p.Name) + columns = append(columns, toSnake(p.Name)) value := reflect.ValueOf(m).Elem().FieldByName(p.Name) values = append(values, value.Interface()) } @@ -34,6 +35,43 @@ func quoteMap(values []string) (results []string) { } return } +func toSnake(s string) string { + buf := bytes.NewBufferString("") + for i, v := range s { + if i > 0 && v >= 'A' && v <= 'Z' { + buf.WriteRune('_') + } + buf.WriteRune(v) + } + return strings.ToLower(buf.String()) +} + +func interfaceToSnake(f interface{}) string { + t := reflect.TypeOf(f) + for { + c := false + switch t.Kind() { + case reflect.Array, reflect.Chan, reflect.Map, reflect.Ptr, reflect.Slice: + t = t.Elem() + c = true + } + if !c { + break + } + } + return toSnake(t.Name()) +} + +func snakeToUpperCamel(s string) string { + buf := bytes.NewBufferString("") + for _, v := range strings.Split(s, "_") { + if len(v) > 0 { + buf.WriteString(strings.ToUpper(v[:1])) + buf.WriteString(v[1:]) + } + } + return buf.String() +} func debug(value interface{}) { fmt.Printf("***************\n")