mirror of https://github.com/go-gorm/gorm.git
Add some utils methods stolen from hood
This commit is contained in:
parent
fb3da1f963
commit
9ef4a2669c
2
sql.go
2
sql.go
|
@ -51,7 +51,7 @@ func (s *Orm) query(out interface{}) {
|
||||||
columns, _ := rows.Columns()
|
columns, _ := rows.Columns()
|
||||||
var values []interface{}
|
var values []interface{}
|
||||||
for _, value := range columns {
|
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...)
|
s.Error = rows.Scan(values...)
|
||||||
}
|
}
|
||||||
|
|
40
utils.go
40
utils.go
|
@ -1,6 +1,7 @@
|
||||||
package gorm
|
package gorm
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"bytes"
|
||||||
"fmt"
|
"fmt"
|
||||||
"reflect"
|
"reflect"
|
||||||
"strings"
|
"strings"
|
||||||
|
@ -12,7 +13,7 @@ func modelValues(m interface{}) (columns []string, values []interface{}) {
|
||||||
for i := 0; i < typ.NumField(); i++ {
|
for i := 0; i < typ.NumField(); i++ {
|
||||||
p := typ.Field(i)
|
p := typ.Field(i)
|
||||||
if !p.Anonymous {
|
if !p.Anonymous {
|
||||||
columns = append(columns, p.Name)
|
columns = append(columns, toSnake(p.Name))
|
||||||
value := reflect.ValueOf(m).Elem().FieldByName(p.Name)
|
value := reflect.ValueOf(m).Elem().FieldByName(p.Name)
|
||||||
values = append(values, value.Interface())
|
values = append(values, value.Interface())
|
||||||
}
|
}
|
||||||
|
@ -34,6 +35,43 @@ func quoteMap(values []string) (results []string) {
|
||||||
}
|
}
|
||||||
return
|
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{}) {
|
func debug(value interface{}) {
|
||||||
fmt.Printf("***************\n")
|
fmt.Printf("***************\n")
|
||||||
|
|
Loading…
Reference in New Issue