From 5cfad9d35b7d682ae2c964818424e92a090f1d5f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Sat, 26 Oct 2013 16:29:39 +0800 Subject: [PATCH] Add model.go file --- model.go | 48 ++++++++++++++++++++++++++++++++++++++++++++++++ orm.go | 2 ++ sql.go | 2 +- utils.go | 14 -------------- 4 files changed, 51 insertions(+), 15 deletions(-) create mode 100644 model.go diff --git a/model.go b/model.go new file mode 100644 index 00000000..ada1d447 --- /dev/null +++ b/model.go @@ -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 +} diff --git a/orm.go b/orm.go index 98c13f1a..8d2ad438 100644 --- a/orm.go +++ b/orm.go @@ -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 diff --git a/sql.go b/sql.go index fdf5ff1c..244b9206 100644 --- a/sql.go +++ b/sql.go @@ -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, diff --git a/utils.go b/utils.go index df6853de..138b8e44 100644 --- a/utils.go +++ b/utils.go @@ -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 {