Move get table name methods to model.go

This commit is contained in:
Jinzhu 2013-10-26 16:33:59 +08:00
parent 5cfad9d35b
commit 73cac58998
3 changed files with 24 additions and 21 deletions

View File

@ -1,6 +1,10 @@
package gorm package gorm
import "reflect" import (
"regexp"
"reflect"
)
type Model struct { type Model struct {
Data interface{} Data interface{}
@ -26,6 +30,23 @@ func (m *Model) ColumnsAndValues() (columns []string, values []interface{}) {
return return
} }
func (m *Model) TableName() string {
t := reflect.TypeOf(m.Data)
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
}
}
reg, _ := regexp.Compile("s*$")
return reg.ReplaceAllString(toSnake(t.Name()), "s")
}
func (m *Model) Columns() (columns []string) { func (m *Model) Columns() (columns []string) {
typ := reflect.TypeOf(m.Data).Elem() typ := reflect.TypeOf(m.Data).Elem()

2
orm.go
View File

@ -26,7 +26,7 @@ type Orm struct {
func (s *Orm) setModel(model interface{}) (err error) { func (s *Orm) setModel(model interface{}) (err error) {
s.Model = toModel(model) s.Model = toModel(model)
s.TableName = interfaceToTableName(model) s.TableName = s.Model.TableName()
s.PrimaryKey = "id" s.PrimaryKey = "id"
return return
} }

View File

@ -3,8 +3,7 @@ package gorm
import ( import (
"bytes" "bytes"
"fmt" "fmt"
"reflect"
"regexp"
"strings" "strings"
) )
@ -45,23 +44,6 @@ func snakeToUpperCamel(s string) string {
return buf.String() return buf.String()
} }
func interfaceToTableName(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
}
}
reg, _ := regexp.Compile("s*$")
return reg.ReplaceAllString(toSnake(t.Name()), "s")
}
func debug(value interface{}) { func debug(value interface{}) {
fmt.Printf("***************\n") fmt.Printf("***************\n")
fmt.Printf("%+v\n\n", value) fmt.Printf("%+v\n\n", value)