mirror of https://github.com/go-gorm/gorm.git
If failed to update current record with Save, try to create a new one
This commit is contained in:
parent
446ce99a42
commit
02f6ae3c4e
10
main.go
10
main.go
|
@ -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
|
||||
func (s *DB) Save(value interface{}) *DB {
|
||||
scope := s.clone().NewScope(value)
|
||||
if scope.PrimaryKeyZero() {
|
||||
return scope.callCallbacks(s.parent.callbacks.creates).db
|
||||
if !scope.PrimaryKeyZero() {
|
||||
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
|
||||
|
|
|
@ -81,10 +81,16 @@ func TestStringPrimaryKey(t *testing.T) {
|
|||
ID string `gorm:"primary_key"`
|
||||
Name string
|
||||
}
|
||||
DB.DropTable(&UUIDStruct{})
|
||||
DB.AutoMigrate(&UUIDStruct{})
|
||||
|
||||
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")
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue