Add some utils methods stolen from hood

This commit is contained in:
Jinzhu 2013-10-26 14:23:02 +08:00
parent fb3da1f963
commit 9ef4a2669c
2 changed files with 40 additions and 2 deletions

2
sql.go
View File

@ -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...)
}

View File

@ -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")