If failed to update current record with Save, try to create a new one

This commit is contained in:
Jinzhu 2016-09-07 21:54:19 +08:00
parent 446ce99a42
commit 02f6ae3c4e
2 changed files with 15 additions and 5 deletions

10
main.go
View File

@ -363,10 +363,14 @@ func (s *DB) UpdateColumns(values interface{}) *DB {
// Save update value in database, if the value doesn't have primary key, will insert it // Save update value in database, if the value doesn't have primary key, will insert it
func (s *DB) Save(value interface{}) *DB { func (s *DB) Save(value interface{}) *DB {
scope := s.clone().NewScope(value) scope := s.clone().NewScope(value)
if scope.PrimaryKeyZero() { if !scope.PrimaryKeyZero() {
return scope.callCallbacks(s.parent.callbacks.creates).db newDB := scope.callCallbacks(s.parent.callbacks.updates).db
if newDB.Error == nil && newDB.RowsAffected == 0 {
return s.New().FirstOrCreate(value)
} }
return scope.callCallbacks(s.parent.callbacks.updates).db return newDB
}
return scope.callCallbacks(s.parent.callbacks.creates).db
} }
// Create insert the value into database // Create insert the value into database

View File

@ -81,10 +81,16 @@ func TestStringPrimaryKey(t *testing.T) {
ID string `gorm:"primary_key"` ID string `gorm:"primary_key"`
Name string Name string
} }
DB.DropTable(&UUIDStruct{})
DB.AutoMigrate(&UUIDStruct{}) DB.AutoMigrate(&UUIDStruct{})
data := UUIDStruct{ID: "uuid", Name: "hello"} data := UUIDStruct{ID: "uuid", Name: "hello"}
if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" { if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" || data.Name != "hello" {
t.Errorf("string primary key should not be populated")
}
data = UUIDStruct{ID: "uuid", Name: "hello world"}
if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" || data.Name != "hello world" {
t.Errorf("string primary key should not be populated") t.Errorf("string primary key should not be populated")
} }
} }