Use tag to set primary key

This commit is contained in:
Jinzhu 2014-07-29 18:21:36 +08:00
parent f56e071375
commit 0c63e57f5c
6 changed files with 20 additions and 5 deletions

View File

@ -891,7 +891,7 @@ If you have an existing database schema, and the primary key field is different
```go ```go
type Animal struct { type Animal struct {
AnimalId int64 `primaryKey:"yes"` AnimalId int64 `gorm:"primary_key:yes"`
Birthday time.Time Birthday time.Time
Age int64 Age int64
} }

View File

@ -56,6 +56,17 @@ func TestCreate(t *testing.T) {
} }
} }
func TestCreateWithNoStdPrimaryKey(t *testing.T) {
animal := Animal{Name: "Ferdinand"}
if db.Save(&animal).Error != nil {
t.Errorf("No error should happen when create an record without std primary key")
}
if animal.Counter == 0 {
t.Errorf("No std primary key should be filled value after create")
}
}
func TestAnonymousScanner(t *testing.T) { func TestAnonymousScanner(t *testing.T) {
user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}} user := User{Name: "anonymous_scanner", Role: Role{Name: "admin"}}
db.Save(&user) db.Save(&user)

View File

@ -45,7 +45,7 @@ func (s *DB) print(v ...interface{}) {
} }
func (s *DB) log(v ...interface{}) { func (s *DB) log(v ...interface{}) {
if s.logMode == 2 { if s != nil && s.logMode == 2 {
s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...) s.print(append([]interface{}{"log", fileWithLineNum()}, v...)...)
} }
} }

View File

@ -253,7 +253,10 @@ func (scope *Scope) Fields() []*Field {
field.IsBlank = isBlank(value) field.IsBlank = isBlank(value)
// Search for primary key tag identifier // Search for primary key tag identifier
field.isPrimaryKey = scope.PrimaryKey() == field.DBName || fieldStruct.Tag.Get("primaryKey") != "" settings := parseTagSetting(fieldStruct.Tag.Get("gorm"))
if _, ok := settings["PRIMARY_KEY"]; scope.PrimaryKey() == field.DBName || ok {
field.isPrimaryKey = true
}
if field.isPrimaryKey { if field.isPrimaryKey {
scope.primaryKey = field.DBName scope.primaryKey = field.DBName

View File

@ -119,7 +119,7 @@ func (i *Num) Scan(src interface{}) error {
} }
type Animal struct { type Animal struct {
Counter int64 `primaryKey:"yes"` Counter int64 `gorm:"primary_key:yes"`
Name string Name string
From string //test reserved sql keyword as field name From string //test reserved sql keyword as field name
CreatedAt time.Time CreatedAt time.Time

View File

@ -106,7 +106,8 @@ func GetPrimaryKey(value interface{}) string {
continue continue
} }
if fieldStruct.Tag.Get("primaryKey") != "" { settings := parseTagSetting(fieldStruct.Tag.Get("gorm"))
if _, ok := settings["PRIMARY_KEY"]; ok {
return fieldStruct.Name return fieldStruct.Name
} }
} }