From 331d8ceabdff5ebf4dc2aba2ccc19772ba2db17f Mon Sep 17 00:00:00 2001 From: Jinzhu Date: Mon, 1 Jun 2015 11:04:11 +0800 Subject: [PATCH] Don't overwrite primary key if already it is already exist --- callback_create.go | 2 +- main_test.go | 12 ++++++++++++ 2 files changed, 13 insertions(+), 1 deletion(-) diff --git a/callback_create.go b/callback_create.go index b21df08b..e7ec40bb 100644 --- a/callback_create.go +++ b/callback_create.go @@ -70,7 +70,7 @@ func Create(scope *Scope) { id, err := result.LastInsertId() if scope.Err(err) == nil { scope.db.RowsAffected, _ = result.RowsAffected() - if primaryField != nil { + if primaryField != nil && primaryField.IsBlank { scope.Err(scope.SetColumn(primaryField, id)) } } diff --git a/main_test.go b/main_test.go index b547534c..666ba564 100644 --- a/main_test.go +++ b/main_test.go @@ -61,6 +61,18 @@ func init() { runMigration() } +func TestStringPrimaryKey(t *testing.T) { + type UUIDStruct struct { + ID string `gorm:"primary_key"` + Name string + } + + data := UUIDStruct{ID: "uuid", Name: "hello"} + if err := DB.Save(&data).Error; err != nil || data.ID != "uuid" { + t.Errorf("string primary key should not be populated") + } +} + func TestExceptionsWithInvalidSql(t *testing.T) { var columns []string if DB.Where("sdsd.zaaa = ?", "sd;;;aa").Pluck("aaa", &columns).Error == nil {