Add model.go file

This commit is contained in:
Jinzhu 2013-10-26 16:29:39 +08:00
parent 95b7263ec7
commit 5cfad9d35b
4 changed files with 51 additions and 15 deletions

48
model.go Normal file
View File

@ -0,0 +1,48 @@
package gorm
import "reflect"
type Model struct {
Data interface{}
}
func toModel(value interface{}) *Model {
var model Model
model.Data = value
return &model
}
func (m *Model) ColumnsAndValues() (columns []string, values []interface{}) {
typ := reflect.TypeOf(m.Data).Elem()
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
columns = append(columns, toSnake(p.Name))
value := reflect.ValueOf(m.Data).Elem().FieldByName(p.Name)
values = append(values, value.Interface())
}
}
return
}
func (m *Model) Columns() (columns []string) {
typ := reflect.TypeOf(m.Data).Elem()
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
columns = append(columns, toSnake(p.Name))
}
}
return
}
func (model *Model) MissingColumns() (results []string) {
return
}
func (model *Model) ColumnType(column string) (result string) {
return
}

2
orm.go
View File

@ -13,6 +13,7 @@ type Orm struct {
Error error
Sql string
SqlVars []interface{}
Model *Model
db *sql.DB
whereClause []map[string]interface{}
@ -24,6 +25,7 @@ type Orm struct {
}
func (s *Orm) setModel(model interface{}) (err error) {
s.Model = toModel(model)
s.TableName = interfaceToTableName(model)
s.PrimaryKey = "id"
return

2
sql.go
View File

@ -71,7 +71,7 @@ func (s *Orm) query(out interface{}) {
}
func (s *Orm) saveSql(value interface{}) {
columns, values := modelValues(value)
columns, values := s.Model.ColumnsAndValues()
s.Sql = fmt.Sprintf(
"INSERT INTO \"%v\" (%v) VALUES (%v)",
s.TableName,

View File

@ -8,20 +8,6 @@ import (
"strings"
)
func modelValues(m interface{}) (columns []string, values []interface{}) {
typ := reflect.TypeOf(m).Elem()
for i := 0; i < typ.NumField(); i++ {
p := typ.Field(i)
if !p.Anonymous {
columns = append(columns, toSnake(p.Name))
value := reflect.ValueOf(m).Elem().FieldByName(p.Name)
values = append(values, value.Interface())
}
}
return
}
func valuesToBinVar(values []interface{}) string {
var sqls []string
for index, _ := range values {