yay, support primary key

This commit is contained in:
Jinzhu 2013-10-26 17:56:00 +08:00
parent 3c68efc94a
commit a7f62c24b0
3 changed files with 33 additions and 4 deletions

View File

@ -23,6 +23,10 @@ func (s *Orm) toModel(value interface{}) *Model {
return &Model{Data: value, driver: s.driver}
}
func (m *Model) PrimaryKey() string {
return "Id"
}
func (m *Model) Fields() (fields []Field) {
typ := reflect.TypeOf(m.Data).Elem()
@ -33,7 +37,11 @@ func (m *Model) Fields() (fields []Field) {
field.Name = p.Name
field.DbName = toSnake(p.Name)
field.Value = reflect.ValueOf(m.Data).Elem().FieldByName(p.Name).Interface()
if m.PrimaryKey() == p.Name {
field.SqlType = getPrimaryKeySqlType(m.driver, field.Value, 0)
} else {
field.SqlType = getSqlType(m.driver, field.Value, 0)
}
fields = append(fields, field)
}
}

2
orm.go
View File

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

View File

@ -5,6 +5,27 @@ import (
"time"
)
func getPrimaryKeySqlType(adaptor string, column interface{}, size int) string {
switch adaptor {
case "mysql":
suffix_str := " NOT NULL AUTO_INCREMENT PRIMARY KEY"
switch column.(type) {
case int, int8, int16, int32, uint, uint8, uint16, uint32:
return "int" + suffix_str
case int64, uint64:
return "bigint" + suffix_str
}
case "postgres":
switch column.(type) {
case int, int8, int16, int32, uint, uint8, uint16, uint32:
return "serial"
case int64, uint64:
return "bigserial"
}
}
panic("unsupported sql adaptor, please submit an issue in github")
}
func getSqlType(adaptor string, column interface{}, size int) string {
switch adaptor {
case "mysql":
@ -55,7 +76,7 @@ func getSqlType(adaptor string, column interface{}, size int) string {
default:
panic("invalid sql type")
}
}
default:
panic("unsupported sql adaptor, please submit an issue in github")
}
}